mardi 27 octobre 2015

How to render validation errors of form partial - Rails

So i am building a custom blog. So i have posts and comments.

I render comments through a partial on the show action of individual posts.

posts controller

 class Blog::PostsController < Blog::BaseController

  def show
    @post = Post.find_by_permalink(params[:id])
    @comment = Comment.new(:post => @post)
  end

end

comments controller

class Blog::CommentsController < Blog::BaseController

  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      flash[:success] = "Comment successfully created!"
      redirect_to blog_post_url(@comment.post)
    else
      flash[:warning] = "Something went wrong, try again. If problem persists please let our team know about it!"
      redirect_to :back
    end
  end

  private
      def comment_params
        params.require(:comment).permit(:body,:name,:email,:user_id,:post_id)
      end
end

and the show.html.erb

<div class="row post-container">
  <div class="large-offset-1 large-7 medium-12 columns post-content">
    <h1 class="post-title"> <%= link_to @post.title, blog_post_path(@post) %> </h1>
    <p class="published-date"><em>Published on <%= l @post.published_at, format: :date %></em></p>

    <div class="post-body">
      <%= @post.body.html_safe %>
      <%= render partial: "blog/comments/comment", post: @post %>
    </div>
  </div>
  <div class="large-4 columns sidebar">
    sidebar
  </div>
</div>

comments partial form

<%= form_for [:blog,@comment] do |f| %>
  <%= render 'blog/shared/error_messages', object: f.object %>

  <div class="field panel">
    <%= f.label :name %><br>
    <%= f.text_field :name,class: 'form-control' %>
  </div>

  <div class="field panel">
    <%= f.label :email %><br>
    <%= f.text_field :email,class: 'form-control' %>
  </div>

  <div class="field panel">
    <%= f.label :body, "Comment" %><br>
    <%= f.text_area :body,class: 'form-control' %>
  </div>

  <% if logged_in? %>
    <%= f.hidden_field :user_id, value: current_user.id %>
  <% end %>

  <%= f.hidden_field :post_id %>



  <div class="actions">
    <%= f.submit "Create comment", class:"btn btn-danger btn-block" %>
    <a class="btn btn-warning btn-block cancel">Cancel</a>
  </div>
<% end %>

so i tried to put validations on the comments model but it does not display them even though it correctly redirects back.

i know i have to use render instead of redirect but i do not know what to render and that is what i am trying to figure out since i do not have a render new action.

Aucun commentaire:

Enregistrer un commentaire