【问题标题】:simple_form association field not pre-selecting selected elementssimple_form 关联字段未预选选定元素
【发布时间】:2014-05-20 20:18:24
【问题描述】:

我在 Rails 中有一个带有“虚拟”关联的 Message 数据模型。也就是说,一个返回“关联对象”集合的方法,但它不是 ActiveRecord 意义上的实际关联。

class Message
  def recipients
    @recipients
  end

  def recipients=(arr)
    @recipients = arr
  end
end

simple_form 的问题是,当我尝试显示 association 字段时,它会失败,因为没有 :recipients 关联:

= simple_form_for(@message) do |f|
  = f.association :recipients, collection: Recipient.all

解决方案看起来很简单,我继续使用 f.inputas: :select 选项:

= simple_form_for(@message) do |f|
  = f.input :recipients, as: :select, collection: Recipient.all

这很好用,除了它不会自动检测@message.recipients 中已有的值,因此在呈现表单时元素会显示为预选。

如果Message#recipients 是一个实际的关联,在ActiveRecord 的意义上,那么表单中的f.association 也会这样做。但由于超出此问题范围的原因,我无法将其作为实际关联。

那么问题来了,能不能实现f.input :recipients, as: :select预选元素呢?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations simple-form


    【解决方案1】:

    嗯,这很尴尬。就在发布这个之后,我想出了一个最终解决问题的想法:

    class Message
      # ...
    
      def recipient_ids
        # ...
      end
    
      def recipient_ids=(arr)
        # ...
      end
    end
    

    我添加了recipient_ids getter 和 setter,除了我之前拥有的关联 getter 和 setter。

    然后我更新了表单输入字段以引用:recipient_ids 而不是:recipients

    = simple_form_for(@message) do |f|
      = f.input :recipient_ids, as: :select, collection: Recipient.all
    

    【讨论】:

      猜你喜欢
      • 2011-07-26
      • 1970-01-01
      • 2012-01-15
      • 2013-09-19
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2011-06-18
      • 2017-09-18
      相关资源
      最近更新 更多