Simpleform中的多态关联

Pas*_*per 10 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

以下型号:

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
Run Code Online (Sandbox Code Playgroud)

抛出以下错误:

uninitialized constant Chat::Chattable
Run Code Online (Sandbox Code Playgroud)

min*_*gle 13

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

= f.input :chattable, collection: @chat.chattables, selected: f.object.chattable.try(:signature),
Run Code Online (Sandbox Code Playgroud)

然后在聊天模型中:

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

  def chattable=(attribute)
    self.chattable_id, self.chattable_type = attribute.split(',')
  end
Run Code Online (Sandbox Code Playgroud)

在你的PylymorphicModel中

  def signature
    [id, type].join(",")
  end
Run Code Online (Sandbox Code Playgroud)

如果您使用聊天表,请记住添加聊天表.


Nar*_*tor 5

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

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

SimpleForm需要确定关联的类.由于默认情况是关联名称是类的去大写的名称,它最终会查找类"Chattable",并且找不到它,这是您的错误来自的地方.

好消息是,您需要做的就是用f.association :chattable符合您需要的东西替换线路.http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease有你需要的信息"简单方法" - 也就是说,使用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)
...
Run Code Online (Sandbox Code Playgroud)

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

  • 没问题!解决问题很有趣,现在我更了解Rails的工作原理. (2认同)