I've been poking around this site and web and cannot find the error of
my ways here. I have a HABTM relationship between models User and Site.
I'm trying to create a few users in script/console and not having any
luck getting it to save.
u = User.find(:first) <-- returns an object
u.sites <-- returns as I expect
u.sites = [1,2] <-- gives me the following error:
ActiveRecord::AssociationTypeMismatch: Site expected, got Fixnum
I have checked my migrations and tables and everything seems to be in
order. Thanks in advance to anyone that can lend me a hand.
As it happens, neither do I What effect do you want to bring
about
exactly?
Thanks for the reply, David. I was just browsing your book looking for
some help
I am trying to create rows in the empty join table sites_users (user_id,
site_id). I assumed that once I had the user object, I could just assign
sites to him by passing it an array.
It helps, but you need to pass actual Site objects in the array. To
find and pass in the sites with ids 1 and 2, you would do this:
user.sites << Site.find(1,2)
Thanks, David, it worked like a charm! I think I was getting confused by
my experiment with checkboxes in a view and expected it to work the same
way in console.
I was about to say: but that will replace the whole collection... but
on rechecking the thread I see that that's what the OP was trying to
do Somewhere along the line I accidentally switched to appending.
David
Aha! Okay, thanks to you both for the great replies. More than just
using Rails, I'm really trying to master Ruby (and programming), so both
recommendations have been very insightful. Thanks to you both!