2012-01-06 128 views
0

我有一個「grouped_collection_select」爲「分支」字段,結合「扇區」字段。部門的has_many分公司和分支機構belongs_to的部門:grouped_collection_select返回錯誤

<%= f.grouped_collection_select(:branch, current_user.company.sectors.order(:sector), :branches, :sector, :id, :branch, include_blank: true) %> 

這工作,但「:分支」顯示所有分支機構,應只顯示current_user.company的分支,就像sectord。但是,當我改變「:分支」到「current_user.company.branches.order(:分支)」,我得到一個錯誤:

(eval):1: syntax error, unexpected $end group.#<ActiveRecord 

什麼我錯在這裏做什麼?謝謝!

回答

0

爲了清晰(和語義)設置集合中的控制器在視圖中使用:

@sectors = current_user.company.sectors.order(:sector) 

...或者,如果你想限制都呈現由用戶對每個部門的分支,你'd可能希望基於用戶的分支來構建集合。舉個例子:

@sectors = current_user.company.branches.collect{|b| b.sector}.uniq 

然後假設你要設置的branch_id和扇區都有一個name屬性和分支都有一個名字屬性,這應該工作:

<%= f.grouped_collection_select(:branch_id, @sectors, :branches, :name, :id, :name, :include_blank=>true) 

#:branch_id is the attribute you will be setting on the form_builder's object. 
#@sectors is the collection of objects for the groups. 
#:branches is the method that will be called on each sector object. 
#:name is the method that will be called on each sector object to label the group. 
#:id is the method that will be called on each branch to set the option's value. 
#:name is the method that will be called on each branch to set the option's label. 
+0

它的工作好了,但它表明數據庫中的所有分支。它應該只顯示屬於current_user.company的分支,就像扇區一樣。但是使用@branches而不是:分支返回一個錯誤。 – John 2012-01-06 19:09:01

+0

使用:分支與此表達式等價:「current_user.company.sectors.order(:sector).first.branches」請記住,:分支是將在每個扇區上調用的方法的名稱。因此,它只能是一個字符串或一個符號。聽起來像是你的問題,真的是你想要限制該基於該用戶的可訪問分支的@sectors集合。例如,sector = current_user.company.branches.collect {| branch | branch.sector} .uniq – miked 2012-01-06 19:26:46

+0

然後我的結論是,grouped_collection_select不是我可以使用的。相反,我將使用collection_select並根據在扇區列表框中所做的選擇,使用jQuery過濾值。但謝謝你的解釋! – John 2012-01-08 08:37:02