加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:09:59 所属栏目:百科 来源:网络整理
导读:我正在研究我的第一个多态关联关系,我无法重构我的form_for创建注释. 我试过通过Polymorphic Association RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast,但似乎过时了. 我有两个问题: 如何重写我的comment_form部
我正在研究我的第一个多态关联关系,我无法重构我的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读