ruby-on-rails – 重构Form_for为多态关联中的注释创建方法

我正在研究我的第一个多态关联关系,我无法重构我的form_for创建注释.

我试过通过Polymorphic Association RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast,但似乎过时了.

我有两个问题:

>如何重写我的comment_form部分,以便它适用于任何可评论的内容?我现在的方式,它只适用于traveldeals(::commentable_id => @ traveldeal.id).
>当我创建注释时,commentable_type为空.什么是commentable_type,我需要在表单中传递吗?

谢谢!

user.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

comment.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 %>

comments_controller.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

最佳答案 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
点赞