首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的has_many模型中只有一个能工作

为什么我的has_many模型中只有一个能工作
EN

Stack Overflow用户
提问于 2013-09-26 20:26:55
回答 1查看 54关注 0票数 0

我遵循http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast教程,通过关系建立了一个has_many,当我试图从一个模型访问信息时,它起作用,而不是从另一个模型访问信息。

我可以通过@product.category_ids@product.categories访问产品模型中的分类信息,但事实并非如此。我无法从分类模型访问产品信息。使用@category.product_ids@category.products会给出错误NoMethodError: undefined method 'product_ids' for #<Category:0x007fa70d430e98>

Product.rb

代码语言:javascript
复制
class Product < ActiveRecord::Base
  attr_accessible  :category_ids

  has_many :categorizations
  has_many :categories, through: :categorizations
  accepts_nested_attributes_for :categorizations,  :allow_destroy => true
end

Category.rb

代码语言:javascript
复制
class Category < ActiveRecord::Base
  attr_accessible  :product_ids

  has_many :categorizations
  has_many :products, through: :categorizations
end

-编辑--

Schema.rb

代码语言:javascript
复制
ActiveRecord::Schema.define(:version => 20130926192205) do

  create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at",     :null => false
    t.datetime "updated_at",     :null => false
  end

  create_table "products", :force => true do |t|
    t.string   "name"
    t.datetime "created_at",          :null => false
    t.datetime "updated_at",          :null => false
  end

  create_table "categorization", :force => true do |t|
    t.integer  "product_id"
    t.integer  "category_id"
    t.datetime "created_at",     :null => false
    t.datetime "updated_at",     :null => false
  end

  add_index "categorization", ["product_id", "category_id"], :name => "index_categorization_on_product_id_and_category_id", :unique => true
  add_index "categorization", ["product_id"], :name => "index_categorization_on_product_id"
  add_index "categorization", ["category_id"], :name => "index_categorization_on_category_id"

end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-26 21:01:24

要从每个对象访问记录,您应该能够:

代码语言:javascript
复制
@category.products

代码语言:javascript
复制
@product.categories

这将为您提供相关的对象。

product_ids不是类别上的属性,它没有像类别模型那样的accepts_attributes_for :products,因此删除attr_accessible :product_ids应该修复错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19038049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档