2

我正在尝试在 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/”中的产品时,它只会列出所有产品!这是否意味着我的路线设置正确,我只需要在产品控制器上编写一个自定义操作(而不是索引)?我在这里做错了什么......我是接近还是远离?!?

谢谢

4

3 回答 3

3

您可能没有使用路线中的数据来过滤您的产品列表。

在 product_controller 的 index 方法中,您需要执行以下操作:

Category.find(params[:category_id]).products
于 2010-02-05T22:27:41.537 回答
2

您要做的是使用嵌套资源。一般格式如下所示:

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

在此处阅读更多相关信息。

于 2010-02-05T22:23:22.843 回答
0

正如这个问题中所提议的,您可以尝试将请求参数 :category_id 添加到您的查找查询中。

始终查看rake routes的输出。

于 2010-02-05T22:45:04.560 回答