【发布时间】:2012-04-11 21:04:17
【问题描述】:
我正在处理我的第一个多态关联关系,但在重构我的 form_for create cmets 时遇到问题。
我尝试通过多态协会 RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast,但它似乎过时了。
我有两个问题:
如何重写我的 comment_form 部分,以便它适用于任何可评论的内容?按照我现在的方式,它只适用于自
(:commentable_id => @traveldeal.id)以来的 traveldeals。当我创建评论时,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
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 %>
cmets_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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 polymorphic-associations