Reputation: 461
I have the following post controller:
def create
@book = Book.find(params[:book_id])
@post = @book.posts.create(post_params)
if @post.save
redirect_to book_path(@book), notice: "Success!~"
else
redirect_to book_path(@book), alert: "Failure!"
end
end
Exactly same redirect_to
is used for comments. Comment creation form and list are on the same url as the post creation form and list (which is show.html.erb for book)
comments controller create:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to book_path(@book), notice: "Success!~"
else
redirect_to book_path(@book), alert: "Failure!"
end
end
But when I create a comment, this error shows: No route matches {:action=>"show", :controller=>"books", :id=>nil}, missing required keys: [:id]
. The comment is created and saved in the database.
I have tried book
and book.id
instead of @book
. None worked. (interestingly, from books list to show.html.erb
, I can only go there by book_path(book.id)
and not book_path(@book)
).
Here's my book show action, and below it is my show.html.erb for book.
@book = Book.find(params[:id])
@post = @book.posts.new
@comment = Comment.new
show.html.erb:
<%= form_for([@book, @book.posts.build]) do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit "Post"%>
</p>
<% end %>
<% @book.posts.each do |post| %>
<p>
<%= @book.title %>
<%= post.text %>
</p>
<%= form_for(post.comments.build, url: "/posts/#{post.id}/comments") do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit "Post comment"%>
</p>
<% end %>
<% end %>
routes:
resources :users do
resources :books, shallow: true
end
resources :books do
resources :posts, shallow: true
end
resources :posts do
resources :comments, shallow: true
end
Upvotes: 0
Views: 68
Reputation: 3002
The error says it all, you are not supplying an id for the book. Notice how the show route is something like /books/2
where 2
is the id? That number is not getting supplied in the comments controller. It looks to me like comments belong to a post which belongs to a book, so this should solve the issue for you.
if @comment.save
redirect_to book_path(@post.book.id), notice: "Success!~"
else
redirect_to book_path(@post.book.id), alert: "Failure!"
end
In your code you are using @book
but it does not look like you ever set that variable with any values the way you do in the create
method, so there is no id
value there, make sense?
Upvotes: 1