我试图建立2个对象之间的多到许多关联。我已经通过几个教程走了,已经能够正确地建立模型。我的问题是我无法建立正确的路线,所以我可以查看完整的关系...像只显示产品从一个特定的类别( /分类/ 1 /产品/

这是怎么产生的模型:

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_controller的索引方法,你需要做的是这样的:

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

其他提示

您想要做的是使用嵌套资源。一般格式是这样的:

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

了解更多关于它这里

这个问题,你可以尝试添加请求参数:CATEGORY_ID您查找查询

经常关注的耙路线即可。

的输出
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top