Rails 3 Models: Can create/update with :association_id => association.id, but not :association => association
This is a problem I regularly run into, and I'm not quite sure why. Any suggestions appreciated:
Suppose I have a relationship between shop and book (book belongs to shop, shop has many books)
If I run the following code:
shop = Shop.first
Book.new(:name => 'Naked People', :shop => shop)
I'll get
A开发者_开发问答ctiveRecord::AssociationTypeMismatch: Shop(#70161677495100) expected, got String(#70161654862280)
However, if I run
shop = Shop.first
Book.new(:name => 'Naked People', :shop_id => shop.id)
everything works fine.
Other things:
- I don't think it's an attr_accessible problem. I've tried stripping out the attr_accessible call from both models...no change
- I don't think it's a problem with the association. From console, I can create Book.new(:name => 'Naked People', :shop => shop) no problem. At the moment it's from rspec controller tests that things aren't working
Any ideas? I seem to run into this quite often, but am stumped re: the solution
精彩评论