我正在处理我的第一个多态关联关系,并且在重构我的 form_for 创建评论时遇到了麻烦。
我尝试通过多态协会 RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast,但它似乎过时了。
我有两个问题:
如何重写我的 comment_form 部分,以便它适用于任何可评论的内容?我现在拥有它的方式,它只适用于 traveldeals,因为
(:commentable_id => @traveldeal.id)
.当我创建评论时,commentable_type 为空。什么是commentable_type,我需要在表单中传递它吗?
谢谢!
用户.rb
class User < ActiveRecord::Base
has_many :comments, :dependent => :destroy
end
traveldeal.rb
class Traveldeal < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
评论.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
validates :user_id, :presence => true
validates :commentable_id, :presence => true
validates :content, :presence => true
end
traveldeal_show.html.erb
<%= render 'shared/comment_form' %>
_comment_form.html.erb
<%= form_for current_user.comments.build(:commentable_id => @traveldeal.id) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div>
<%= f.text_area :content %>
</div>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :commentable_id %>
<div>
<%= f.submit "Add Comment" %>
</div>
<% end %>
评论控制器.rb
class CommentsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
def create
@comment = Comment.new(params[:comment])
@comment.save
redirect_to root_path
end
end