有没有办法在simple_form
View 中显示多态关联?
到目前为止,我得到了以下信息:
= 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
最佳答案
我找到了不需要 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
如果您使用它们,请记住将 chattable 添加到安全参数中。
关于ruby-on-rails - Simpleform 中的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649147/