ruby 代码
- migration
- create_table :products do |t|
- t.column :name, :string
- t.column :category_id, :integer
- end
- create_table :categories do |t|
- t.column :name, :string
- end
- 10.times { |i|
- c = Category.create(:name => "Category#{i}")
- 2.times { |j|
- Product.create(:name => "Product#{j}", :category => c)
- }
- }
- model
- class Category < ActiveRecord::Base
- has_many :products
- end
- class Product < ActiveRecord::Base
- belongs_to :category
- end
- view
- # option_groups_from_collection_for_select (collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
- # http://railsapi.masuidrive.jp/module/ActionView::Helpers::FormOptionsHelper#option_groups_from_collection_for_select
- <% @categories = Category.find(:all, :include => "products") %>
- <!--select-->
- <%= option_groups_from_collection_for_select(@categories, :products, :name, :id, :name) %>
- <!--/select-->