2010-02-05 53 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您查找查询。

总是看耙路线的输出。