代码之家  ›  专栏  ›  技术社区  ›  Eric Norcross

为什么我的has_many模型中只有一个有效

  •  0
  • Eric Norcross  · 技术社区  · 11 年前

    我紧随其后 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>

    产品.rb

    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
    

    类别.rb

    class Category < ActiveRecord::Base
      attr_accessible  :product_ids
    
      has_many :categorizations
      has_many :products, through: :categorizations
    end
    

    --编辑--

    示意图.rb

    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
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Oliver    11 年前

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

    @category.products
    

    @product.categories
    

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

    product_ids 不是类别上的属性,并且它没有 accepts_attributes_for :products 喜欢你的分类模型,所以删除 attr_accessible :product_ids 应该修复错误。