重构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 :destroy end
traveldeal.rb
class Traveldeal :commentable, :dependent => :destroy end
comment.rb
class Comment true validates :user_id, :presence => true validates :commentable_id, :presence => true validates :content, :presence => true end
traveldeal_show.html.erb
_comment_form.html.erb
@traveldeal.id) do |f| %> f.object %>
comments_controller.rb
class CommentsController [: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| %> <%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit "Submit" %>
<% end %>
如果您这样做,将自动设置commentable_type
。 您需要该类型,以便了解评论所属的模型。 请注意,您必须在使用注释表单的方法中设置@commentable
。
例如
class TraveldealsController < ApplicationController def show @traveldeal = @commentable = Traveldeal.find(params[:id]) end end