无法在帖子RAILS中创建评论表单

时间:2014-04-28 16:13:55

标签: ruby-on-rails ruby-on-rails-4

我正在尝试在rails中的文章下创建一个评论框/表单,但它不断引发错误,说明未知属性:post_id

我的表单代码

<%= form_for ([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %> <br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %> <br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>

我的评论创建动作

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

respond_to do |format|
  if @comment.save
    format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
    format.json { render action: 'show', status: :created, location: @comment }
  else
    format.html { render action: 'new' }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end
end

它会引发错误

<%= form_for ([@post, @post.comments.build]) do |f| %>

说未知属性:post_id

全部谢谢!

更新错误:未定义方法`帖子'

<tr>
       <td><%= comment.commenter %></td>
       <td><%= comment.body %></td>
       <td><%= comment.posts %></td>
       <td><%= link_to 'Show', comment %></td>
       <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
       <td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>

1 个答案:

答案 0 :(得分:2)

好像post_id表中没有导致错误的comments列。

查看您的代码,我猜您希望在PostComment模型之间建立1-M关系。

确保在模型中正确设置关系,如下所示:

class Post < ActiveRecord::Base
  has_many :comments
  ## ...
end

class Comment < ActiveRecord::Base
  belongs_to :post
  ## ...
end

在此之后,您必须在post_id表中创建comments列作为对posts表的引用。这应解决您的unknown attribute: post_id错误。

您可以通过生成迁移来在post_id表中创建comments列:

rails generate migration AddPostRefToComments post:references

此次运行后rake db:migrate

<强>更新

  

我得到了未定义的方法`post_comments_path'

为了解决上述问题,您应该在routes.rb

中设置嵌套路由
resources :posts do
  resources :comments
end

更新2

更改

<td><%= comment.posts %></td>

<td><%= comment.post %></td>

注意单数post而不是复数posts