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). 谢谢! 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |