我正在努力在我的手上安装act_as_commentable插件
Rails 3应用程序。

在将“ acts_as_commentable”添加到我的书本模型后,然后添加了
我的书展视图上的评论表:

<% form_for(@comment) do|f| %>
  <%= f.hidden_field :book_id %>
  <%= f.label :comment %><br />
  <%= f.text_area :comment %>
  <%= f.submit "Post Comment" %>
<% end %>


然后在控制器(comments_controller.rb)中,

  def create
    @comment = Comment.new(params[:comment])
    Book.comments.create(:title => "First comment.", :comment => "This
is the first comment.")
  end


然后,在提交评论时,它将返回错误:“未知
属性:book_id”
从日志中:

  Processing by CommentsController#create as HTML
  Parameters: {"comment"=>{"comment"=>"WOOOW", "book_id"=>"32"},
"commit"=>"Post Comment",
"authenticity_token"=>"5YbtEMpoQL1e9coAIJBOm0WD55vB2XRZMJa4MMAR1YI=",
"utf8"=>"✓"}
Completed   in 11ms
ActiveRecord::UnknownAttributeError (unknown attribute: book_id):
  app/controllers/comments_controller.rb:3:in `new'
  app/controllers/comments_controller.rb:3:in `create'


有什么建议吗?

最佳答案

我认为您必须选择:

选项1)
风景:

<% form_for(@comment) do|f| %>
  <%= f.hidden_field :commentable_id, :value => @book.id %>
  <%= f.hidden_field :commentable_type, :value => 'Book' %>
  <%= f.label :comment %><br />
  <%= f.text_area :comment %>
  <%= f.submit "Post Comment" %>
<% end %>


控制器:

def create
  @comment = Comment.create(params[:comment])
end


选项2)

在控制器中:

def create
  @book = Book.find(params[:comment][:book_id])
  @comment = @book.comments.create(params[:comment].except([:comment][:book_id]))
end


我没有测试代码,但是这个想法应该是正确的

鉴于您想对各种模型发表评论,请进行更新(我正在编写我的代码而未对其进行测试...)。假设您有书籍和杂志,并且想对它们发表评论。我想我会为它们定义嵌套的路由。

map.resources :books, :has_many => :comments
map.resources :magazines, :has_many => :comments


然后可以在您的控制器中执行以下操作:

before_filter :find_commentable

def find_commentable
  @commentable = Book.find(params[:book_id]) if params[:book_id]
  @commentable = Magazine.find(params[:magazine_id]) if params[:magazine_id]
end


在新视图中:

<% form_for :comment, [@commentable, @comment] do |f| %>
  <%= f.label :comment %>
  <%= f.text_area :comment %>
  <%= f.submit %>
<% end %>


因此,创建动作可能类似于:

def create
  @user.comments.create(params[:comment].merge(:commentable_id => @commentable.id, :commentable_type => @commentable.class.name))
  redirect_to @commentable
end


也许还有更好的方法来做...

10-02 11:39