Accessing the join association model


I have a many-to-many association implementing using association join

class Source
has_many :source_users
has_many :users, :through => :source_users

class SourceUser
belongs_to :source
belongs_to :user

class User
has_many :source_users
has_many :users, :through => :source_users

The source_users table also contains a field called source_admin,
which marks the current user as an admin for this source. When I
create a new user with:

some_source.users << new_user

, how do I insert “true” or “false” in the source_admin field of the
SourceUser record that gets created?


It depends upon how you create the new user. Typically, if the user is
created via data in a params, you might have something like:

@user =[:user])

So, two things. You could do:

@user =[:user])
@user.source_admin = true
some_source.users << @user

(and that last one, I believe will also save it unless it fails

Or you could merge the source_admin with the params:

@user =[:user].merge!(:source_admin => true))
some_source.users << @user

The first option is better if you need to add some logic hooks, i.e.:

@user.source_admin = true unless XYZ




This is what I ended up doing. I thought there is a funky Rails way to
do it, but I guess not.

Thanks for the help,

Maybe there’s a way to do it in less lines. But for me at least, if
it’s clear and it works, why worry? I used to get wrapped around the
axle over that until I realized that sometimes taking a few lines to
do something so it’s easy to read and follow is better than doing it
all in one line.


Woops! I didn’t read your original post very clearly. I think you are
having this problem:

So one way is to simply do:

source = Source.find(id)
user =[:user])
sourceuser = => source, :user =>
user, :source_admin => true)

Then I think just calling:

will also save the new user. But you’ll want to double-check that.

Is that what you were looking for?