2014-02-22 41 views
0

我已經成功地將formtastic集成到了我的rails項目中,並用它在多對多關係中進行多值選擇。在多對多中限制Formtastic集合

問題是,我似乎無法找到如何限制選擇那些相關的。

考慮以下幾點:

class Pool < ActiveRecord::Base 
has_many :poolings, dependent: :destroy 
has_many :commercials, :through => :poolings 
accepts_nested_attributes_for :poolings 
accepts_nested_attributes_for :commercials 
belongs_to :client 
end 

的關係多到多模

class Pooling < ActiveRecord::Base 
belongs_to :pool 
belongs_to :commercial 
end 

和商業模式

class Commercial < ActiveRecord::Base 
belongs_to :client 
has_many :poolings, dependent: :destroy 
has_many :pool, :through => :poolings 
end 

下面的代碼工作創造了多個選擇形式:

<%= semantic_form_for @pool do |f| %> 
    <%= f.inputs %> 
    <%= f.inputs :commercials %> 
    <%= f.actions %> 
<% end %> 

關鍵是formtastic的假設:商業廣告翻譯成多對多的選擇形式。

現在閱讀文檔,我不明白添加到線

<%= f.inputs :commercials %> 

所以,當我在窗體中使用它來編輯一個「池子」裏的「CLIENT_ID = 1」時,將只顯示我的「廣告」與「CLIENT_ID = 1

使用與收集以下選擇給了我預期的結果:

<%= f.collection_select :commercials, Commercial.where(:client_id => @pool.client), :id, :name %> 

什麼是formtast相當於我知道了?

順便說一句,剛剛接觸RoR我發現很混亂,各種組件和寶石似乎都略有不同。開源的喜悅!

回答

0

選擇,複選框和收音機有一個「收集」參數(請參閱Usage)。

爲了您的具體問題,解決方案可以是這個樣子:

<%= semantic_form_for @pool do |f| %> 
    <%= f.inputs do %> 
    <%= f.input :commercials, :collection => Commercial.where(:client_id => @pool.client) %> 
    <% end %> 
    <%= f.actions %> 
<% end %>