我正在尝试在 2 个对象之间建立多对多关联。我已经阅读了几个教程,并且能够正确设置模型。我的问题是我无法设置正确的路线,因此我可以查看完整的关系......就像只显示特定类别的产品(/categories/1/products/)
这就是我生成模型的方式:
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
当我尝试查看类别“/categories/7/products/”中的产品时,它只会列出所有产品!这是否意味着我的路线设置正确,我只需要在产品控制器上编写一个自定义操作(而不是索引)?我在这里做错了什么......我是接近还是远离?!?
谢谢