Ruby on rails 相同的重定向到路由,对帖子有效,对评论无效(相同的url)

Ruby on rails 相同的重定向到路由,对帖子有效,对评论无效(相同的url),ruby-on-rails,Ruby On Rails,我有以下职位控制员: 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

我有以下职位控制员:

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
注释使用完全相同的
redirect_to
。评论创建表单和列表与帖子创建表单和列表位于同一个url上(对于book是show.html.erb)

控制器创建的注释:

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
但是当我创建注释时,这个错误显示:
没有路由匹配{:action=>“show”,:controller=>“books”,:id=>nil},缺少必需的键:[:id]
。注释将被创建并保存在数据库中

我尝试了
book
book.id
而不是
@book
。没有一个奏效。(有趣的是,从图书列表到
show.html.erb
,我只能通过
book\u路径(book.id)
到达那里,而不能通过
book\u路径(@book)

这是我的书show action,下面是我的书show.html.erb

@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 %>

错误说明了一切,您没有为该书提供id。注意,显示路线类似于
/books/2
,其中
2
是id?注释控制器中未提供该数字。在我看来,评论属于一篇文章,属于一本书,所以这应该能为你解决这个问题

if @comment.save
  redirect_to book_path(@post.book.id), notice: "Success!~"
else 
  redirect_to book_path(@post.book.id), alert: "Failure!" 
end

在您的代码中,您使用的是
@book
,但看起来您从未像在
create
方法中那样使用任何值设置该变量,因此那里没有
id
值,有意义吗?

您有
book\u路径(@book)
,但是
@book
没有在您的create方法中定义。您需要
book\u路径(@post.book)
instead@escanxr太好了,谢谢!成功了,谢谢!如果你有机会,如果你能回答这个问题,我会非常感激。。。注释未与此代码一起显示在show.html.erb:

中。是否验证是否保存了注释文本?如果改为放置
comment.id
,它会显示什么吗?
的输出是什么?
为每篇文章返回0。注释保存在数据库中(通过SQL)。。。不确定原因..inspect会为每篇帖子上的每个评论返回
#
。因此,这是您的问题,根据您当前的数据,没有要显示的评论。祝你好运!听起来像是在循环中,您确定没有
@
,is不需要是
post
if @comment.save
  redirect_to book_path(@post.book.id), notice: "Success!~"
else 
  redirect_to book_path(@post.book.id), alert: "Failure!" 
end