2012-01-06 129 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