ruby-on-rails - Simpleform 中的多态关联

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

有没有办法在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/

相关文章:

ruby - Net::HTTP.get 因带有 header 的 HTTPS 失败

ruby-on-rails - 如何销毁两个模型之间的所有关联数据? (Rails 初学者)

ruby-on-rails - 在我的 Rails 答案中删除不必要的 HTTP header

jquery - 防止 Rails AJAX 表单中的重复提交

不同 Windows 版本上的 Ruby Ocra 可执行文件 fatal error

ruby - chef -- 将属性散列传递给资源

forms - Rails 4 form_tag 提交到错误的 Controller 操作

ruby - 我如何在 ruby​​ on rails 中实现 hashids

ruby-on-rails - (如何)我可以使用表单对象进行编辑/更新例程吗?

ruby-on-rails - MultiPolygon 列按迁移