Relationships with Rails

Asked

Viewed 323 times

0

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

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’m not redirected to the post when I create a comment, but to posts/:post_id/comments and another problem is that I can’t create comments! I’m simply redirected to posts/:post_id/comments.

How to solve?

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 post.Rb model:

# 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 table comments that has the post_id column. This post_id needs to be referenced in the allowed parameters. Thus:

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

Having this configured, in the create de comments_controller.Rb method 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 commit. Usually this applies when you want to show the post with/without your comments.

I hope this helps.

  • 0la. For better code organization, comments_controller in a posts/ folder, so the class name is Posts::Commentscontroller. Even so, I need to put has_many and belongs_to?

  • Need because this is the relationship done in the database. Without it in the model will not work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.