我想设置2对象之间的多对多关联。我已经通过了几个教程,并能够正确设置模型。我的问题是我在设置正确的路线时遇到困难,所以我可以查看完整的关系...例如只显示特定类别的产品(/categories/1/products/)正确的路由为:has_many:通过
这是我怎么产生的模型:
script/generate scaffold category name:string
script/generate scaffold product name:string
script/generate scaffold categorization category_id:integer product_id:integer
这里是架构:
ActiveRecord::Schema.define(:version => 20100205210519) do
create_table "categories", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "categorizations", :force => true do |t|
t.integer "category_id"
t.integer "product_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "products", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
这里是3模型对象:
class Category < ActiveRecord::Base
has_many :categorizations
has_many :products, :through => :categorizations
end
class Product < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
很简单,一切似乎是工作的罚款,因为我可以通过控制台添加一个产品类别:
@category.categorizations << Categorization.new(:product_id => 1)
我敢肯定,我需要更新的routes.rb文件,但我不我真的知道正确的做法。这就是我把路线文件:
map.resources :categories, :has_many => :products
当我尝试查看产品上一个类别“/类别/ 7 /产品/”它只是列出了所有的产品!这是否意味着我的路线设置正确,我只需要在产品控制器上编写自定义操作(而不是索引)?我在这里做错了什么......我关闭或离开?!?
谢谢
就是这样......路线设置正确,我只是没有正确处理产品页面上的索引操作。它只是返回默认的“Product.all” – 2010-02-06 14:10:55