Simpleform中的多态关联

时间:2013-12-18 03:25:43

标签: ruby-on-rails ruby ruby-on-rails-4

有没有办法在simple_form视图中显示多态关联?

到目前为止,我已经到了下面:

= simple_form_for(@chat, :html => { :class => "form-horizontal" }, :wrapper => "horizontal", defaults: { :input_html => { class: "form-control"}, label_html: { class: "col-lg-4" } } ) do |f|
    = f.error_notification

    .form-inputs
        = f.association :from_user
        = f.association :to_user
        = f.input :message
        = f.association :chattable

    .form-actions
        = f.button :submit

以下型号:

class Chat < ActiveRecord::Base
    belongs_to :from_user, :foreign_key => 'from_user_id', class_name: 'User'
    belongs_to :to_user, :foreign_key => 'to_user_id', class_name: 'User'
    belongs_to :chattable, polymorphic: true

    validates :from_user, associated: true, presence: true
    validates :message, presence: true
end

这会抛出以下错误:

uninitialized constant Chat::Chattable

2 个答案:

答案 0 :(得分:12)

我发现其他解决方案不需要JS操作,仍然可以使用简单的表单输入。 您可以使用带有id和输入选择的输入选项,以逗号作为选项值传递。

= f.input :chattable, collection: @chat.chattables, selected: f.object.chattable.try(:signature),

然后在聊天模型中:

  def chattables
    PolymorphicModel.your_condition.map {|t| [t.name, t.signature] }
  end

  def chattable=(attribute)
    self.chattable_id, self.chattable_type = attribute.split(',')
  end

在你的PylymorphicModel中

  def signature
    [id, type].join(",")
  end

如果您使用聊天表,请记住将其添加到安全参数中。

答案 1 :(得分:5)

通过大量下摆,唠叨和来回,我们已经确定SimpleForm不会这样做。

这就是为什么! (好吧,可能是为什么)

SimpleForm需要弄清楚关联的类。由于默认情况是关联名称是类的去大写名称,它最终会查找类&#34; Chattable&#34;,并且找不到它,这是您的错误发生的地方从

好消息是,您需要做的就是用满足您需要的东西替换f.association :chattable行。 http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease拥有您执行此操作所需的信息&#34;简单方法&#34; - 又称,与Rails形成帮手。

我的建议是为chattable_type提供一个选择框,以及一些取消隐藏该类型选择框的HTML的JS。所以你得到像

这样的东西
= select_tag(:chattable_type, ["Booth", "Venue"])

= collection_for_select(:chattable_id, Booth.all)
= collection_for_select(:chattable_id, Venue.all)
...

不包括JS和CSS。检查上面链接的文档以获取实际语法;我觉得我有点不对劲。

相关问题