4

我正在处理我的第一个多态关联关系,并且在重构我的 form_for 创建评论时遇到了麻烦。

我尝试通过多态协会 RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast,但它似乎过时了。

我有两个问题:

  1. 如何重写我的 comment_form 部分,以便它适用于任何可评论的内容?我现在拥有它的方式,它只适用于 traveldeals,因为(:commentable_id => @traveldeal.id).

  2. 当我创建评论时,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
4

1 回答 1

2

Railscast 中唯一注明日期的部分是路线。

要回答您的第一个问题:像在 Railscast 中一样创建您的表单:

<%= form_for [@commentable, Comment.new] do |f| %>
  <p>
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </p>
  <p><%= f.submit "Submit" %></p>
<% end %>

如果您这样做,它将commentable_type自动设置。您需要类型,以便知道评论属于哪个模型。请注意,您必须@commentable在使用评论表单的方法中进行设置。

例如

class TraveldealsController < ApplicationController
  def show
    @traveldeal = @commentable = Traveldeal.find(params[:id])
  end
end
于 2012-04-12T02:23:06.790 回答