Question

I followed http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast tutorial to set up a has_many through relationship and when I try to access information from one model it works but not from the other.

I can access the Category information from the Product model via @product.category_ids and @product.categories, but the reverse isn't true. I can't access the Product information from the Category model. Using @category.product_ids or @category.products gives me the error NoMethodError: undefined method 'product_ids' for #<Category:0x007fa70d430e98>

Product.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

Category.rb

class Category < ActiveRecord::Base
  attr_accessible  :product_ids

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

-- EDIT --

Schema.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
Was it helpful?

Solution

To access the records from each object you should be able to:

@category.products

and

@product.categories

That will give you the associated objects.

product_ids is not a attribute on a category and it does not have accepts_attributes_for :products like your category model so removing attr_accessible :product_ids should fix the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top