如何对嵌套资源的评论使用简单的形式?

How to use simple form for comments from a nested resource?

所以我正在创建一个博客 rails 应用程序,并且我正在尝试在该博客上创建一个评论会话。我正在尝试使用简单表单呈现表单,但我很难让简单表单正常工作。现在我有:

<%= simple_form_for ([@user, @post.comments.build]) do |f| %>
  <%= f.input :comment %>
  <%= f.button :submit %>
<% end %>

但它说 post.comments 不是定义的路径。

我的评论模型:

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

post 属于用户,has_many 条评论 用户有很多 post 并且有很多评论

这是我当前的路线:

  resources :posts do
    resources :comments 
  end

有什么建议吗? 谢谢!

为什么要在 simple_form_for 中发送@user?
使用 @post 代替 @user.

从表单中删除用户。

<%= simple_form_for [@post, @post.comments.build] do |f| %>
  <%= f.input :comment %>
  <%= f.button :submit %>
<% end %>

然后,如果您使用的是设计,您将使用 current_user 之类的东西在控制器中分配用户值。

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

def comment_params
  params.require(:comment).permit(:comment)
end

拥有一个名为 comment 的模型和一个名为 comment 的字段是个坏主意。我更愿意称它为 content

我通过为评论生成迁移找到了解决此问题的方法。我只需要确保所有具有关联的东西实际上都在数据库中有列。在那之后,我只是确保我正在渲染@post.comment 而不是comment/comment。希望这对遇到同样问题的任何人有所帮助。