二级下拉选择框option_groups_from_collection_for_select

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
  # attribs: id, name
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  # attribs: id, name
end

class Delivery < ActiveRecord::Base
  belongs_to :recipient, :class_name => "User", :foreign_key => :recipient_id
  # attribs: id, name, recipient_id
end
 

option_groups_from_collection_for_select(Group.all, :users, :name, :id, :name, @delivery.recipient_id)

 

效果:

金工组-------------------group_name

   用户1------------------user_name

铆焊组

   用户2

   用户3

 

api说明:

option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)

Returns a string of <option> tags, like options_from_collection_for_select, but groups them by <optgroup> tags based on the object relationships of the arguments.

Parameters:

  • collection - An array of objects representing the <optgroup> tags.

  • group_method - The name of a method which, when called on a member of collection, returns an array of child objects representing the <option>tags.

  • group_label_method+ - The name of a method which, when called on a member of collection, returns a string to be used as the label attribute for its <optgroup> tag.

  • option_key_method - The name of a method which, when called on a child object of a member of collection, returns a value to be used as thevalue attribute for its <option> tag.

  • option_value_method - The name of a method which, when called on a child object of a member of collection, returns a value to be used as the contents of its <option> tag.

  • selected_key - A value equal to the value attribute for one of the <option> tags, which will have the selected attribute set. Corresponds to the return value of one of the calls to option_key_method. If nil, no selection is made. Can also be a hash if disabled values are to be specified.

Example object structure for use with this method:

class Continent < ActiveRecord::Base
  has_many :countries
  # attribs: id, name
end
class Country < ActiveRecord::Base
  belongs_to :continent
  # attribs: id, name, continent_id
end

Sample usage:

option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)

Possible output:

<optgroup label="Africa">
  <option value="1">Egypt</option>
  <option value="4">Rwanda</option>
  ...
</optgroup>
<optgroup label="Asia">
  <option value="3" selected="selected">China</option>
  <option value="12">India</option>
  <option value="5">Japan</option>
  ...
</optgroup>

Note: Only the <optgroup> and <option> tags are returned, so you still have to wrap the output in an appropriate <select> tag.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值