Saving records in mySQL for many-to-many relationship

Hey guys,

Maybe someone could point out what wrong here. I’ve simplified the issue
to this:
Both User.find(6) and Sport.find(1) exist, Im just trying to setup the
relationship between them.

My controller looks like this

def tester
@c = User.find(6)
@c.sports = Sport.find(1)
end

And I keep getting this error:

undefined method `each’ for #<Sport:0x36a3488
@attributes={“name”=>“Basketball”, “id”=>“1”}>

Im pretty sure that I set up the database right. I have a sports_users
table with sport_id and user_id. And when I put records into the
database manually, the records are finding each other, Im just having
trouble getting this to work from a submit form. Anybody encounter this?

def tester
@c = User.find(6)
@c.sports = Sport.find(1)
end

Does the users table have a sports_id column?

Eric G. wrote:

@c.sports = Sport.find(1)

And I keep getting this error:

undefined method `each’ for #<Sport:0x36a3488
@attributes={“name”=>“Basketball”, “id”=>“1”}>

sports is a collection/array, so you want

@c.sports << Sport.find(1)


We develop, watch us RoR, in numbers too big to ignore.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs