2014-05-20 57 views
1

我有一個Message Rails數據模型與「虛擬」關聯。也就是說,這是一種返回「關聯對象」集合的方法,但它不是ActiveRecord意義上的實際關聯。simple_form關聯字段不預先選擇所選元素

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 

這工作得很好,除了它確實沒有事實t自動檢測@message.recipients中已有的值,以便在表單呈現時預先選擇元素。

如果Message#recipients是一個實際關聯,則在ActiveRecord意義上,那麼表單中的f.association也會這樣做。但是,由於超出了這個問題範圍的原因,我不能把它作爲一個實際的關聯。

接下來的問題是,我可以實現f.input :recipients, as: :select預選所選元素嗎?

回答

2

嗯,這很尷尬。就在發佈此之後,我想出了一個想法,最終解決問題:

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 
相關問題