rob_mccann
rob_mccann

Reputation: 1245

Rails: How to handle belongs_to using nested resources

If I have a nested resource as follows:

resources :posts do
    resources :comments
end

And I visit /posts/1/comments/new, what's the best way of setting the post_id on the Comment model?

Upvotes: 2

Views: 541

Answers (1)

PinnyM
PinnyM

Reputation: 35533

Use form_for:

<%= form_for [@post, @comment] do |f| %>

Alternatively, you can use the longform:

<%= form_for @comment, url: post_comments_path(@post) do |f| %>

It will set the url correctly for you.

Your controller actions should look like this:

def new
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build
end

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment])
  if @comment.save
  ...
end

Upvotes: 2

Related Questions