Reputation: 1245
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
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