Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - has_many association not saving (TypeError)

Store has_many items, and an Item belongs_to Store

I make a new store, save it, all good. I check I can call .items on it.

ruby-1.9.2-p290 :063 > s.items
  Item Load (0.3ms)  SELECT "items".* FROM "items" WHERE "items"."store_id" = 12
 => [] 

But when I try to call create or valid? it returns the following:

ruby-1.9.2-p290 :064 > s.items.create
  Store Load (0.7ms)  SELECT "stores".* FROM "stores" WHERE "stores"."id" = 12 LIMIT 1
TypeError: Cannot visit Store

I've never seen the following error before, so it's doing my head in!


EDIT: After a drop and remigrate, still get the following :

    ruby-1.9.2-p290 :008 > Item.create(:store_id => 5)
  Store Load (0.2ms)  SELECT "stores".* FROM "stores" WHERE "stores"."id" = 5 LIMIT 1
TypeError: Cannot visit Store
like image 613
Galaxy Avatar asked Dec 11 '11 10:12

Galaxy


1 Answers

In case anyone else runs into this issue, It turned out to be a validation issue with the 'Item' model. Originally I had this set up:

  validates :name, :presence => true, uniqueness => { :scope => :store }         

With the scope just set to :store. Turned out I needed to explicitly state :store_id:

  validates :name, :presence => true, uniqueness => { :scope => :store_id }         
like image 154
Galaxy Avatar answered Oct 27 '22 05:10

Galaxy