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-->
本文介绍了一个使用Ruby on Rails实现的产品和类别模型关联的例子,并展示了如何通过数据库迁移创建表结构,定义模型间的关系,以及在视图中利用option_groups_from_collection_for_select方法来显示类别及其关联的产品。
1931

被折叠的 条评论
为什么被折叠?



