我想設置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