Saving many-to-many in script/console

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.

Hi --

As it happens, neither do I :slight_smile: What effect do you want to bring

about

exactly?

Thanks for the reply, David. I was just browsing your book looking for some help :slight_smile:

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.

Does this help or am I digging deeper?

Hi --

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.

-Todd

David A. Black wrote:

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)

You can also do

    user.site_ids = [1,2]

Hi --

David A. Black wrote:

Hi --

   user.site_ids = [1,2]

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 :slight_smile: 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!