2010-02-05 52 views
2

我想設置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 /產品/」它只是列出了所有的產品!這是否意味着我的路線設置正確,我只需要在產品控制器上編寫自定義操作(而不是索引)?我在這裏做錯了什麼......我關閉或離開?!?

謝謝

回答

3

您可能未使用路線中的數據來過濾產品列表。

在product_controller的索引方法,你需要做的是這樣的:

Category.find(params[:category_id]).products 
+0

就是這樣......路線設置正確,我只是沒有正確處理產品頁面上的索引操作。它只是返回默認的「Product.all」 – 2010-02-06 14:10:55

2

你想要做的是使用嵌套資源。一般格式如下所示:

map.resources :users do |users| 
    users.resources :posts 
end 

瞭解更多關於它here

+0

文檔的很好鏈接。瀏覽頁面後,似乎我的路線設置正確。我相信我的路線相當於你寫的路線......根據鐵路線路線指南:http://guides.rubyonrails.org/routing.html#nested-resources – 2010-02-05 23:19:23

+0

爲了完整起見,Ryan的路線是使用(map.resources:categories,:has_many =>:products)也定義了一個嵌套資源,它只是使用不同的格式。 – 2010-02-06 17:31:48

0

this question建議,你可以嘗試添加請求參數:CATEGORY_ID您查找查詢。

總是看耙路線的輸出。