Relationships with Rails

0

I'm doing a small blog in Ruby on Rails, but I'm having problems in the comments section.

In controllers/posts/comments_controller.rb I have the following:

class Posts::CommentsController < ApplicationController

before_filter :require_authentication

def create
    @post = Post.find(params[:post_id])

    @comment = @post.comments.build(comment_params)
    @comment.student_id = current_student.id

    if @comment.save
        redirect_to @post
    end
end

private

def comment_params
    params.require(:comment).permit(:comment)
end

end

In views/posts/_comment.html.erb I have:

<% if student_signed_in? %>
<%= form_for ([@post, @post.comments.build]) do |f| %>
    <p>
        <%= f.label :comment %>
        <%= f.text_area :comment %>
    </p>
    <p><%= f.submit %></p>
<% end %>

And in views/posts/show.html.erb I have:

<%= render 'comment' %>

Two things are going wrong: I am not redirected to the post when I create a comment, but for posts/:post_id/comments and another problem is that I can not create comments! I'm simply redirected to posts/:post_id/comments .

How to solve?

    
asked by anonymous 28.01.2015 / 02:52

1 answer

5

In your case, if it is a post comment, the comment should belong to the post and post should have many comments. First, you need to have in your model post.rb:

# post.rb
class Post < ActiveRecord::Base
  has_many :comments
end

and in comment.rb:

# comment.rb
class Comment < ActiveRecord::Base
  belongs_to :post
end

This relationship needs to be the comments table that has the post_id column. This post_id must be referenced in the allowed parameters. So:

# comments_controller.rb
def comment_params
  params.require(:comment).permit(:body, :post_id)
end

Having this set up, in the create method of comments_controller.rb we have:

# comments_controller.rb
def create
  @post = Post.find(params[:post_id]) # pega post_id para encontrar o post que comentário será relacionado
  @comment = @post.comments.create(comment_params) # cria o comentário conforme os parâmetros passados

  redirect_to post_path(@post) # redireciona para o post definido pelo id na variável @post
end

In this case, I see no need to use the respond_to method for rendering because it is a cometary. Usually, this applies when you want to show the post with / without your comments.

I hope this helps.

    
28.01.2015 / 05:46