accessing the join association model

Hi,

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

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

class SourceUser   belongs_to :source   belongs_to :user end

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?

Thanks, Tiberiu

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.new(params[:user])

So, two things. You could do:

@user = User.new(params[:user]) @user.source_admin = true some_source.users << @user

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

Or you could merge the source_admin with the params:

@user = User.new(params[: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

HTH!

-Danimal

Woops! I didn't read your original post very clearly. I think you are having this problem: has_many :through - Why aren't join models proxy collections?

So one way is to simply do:

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

Then I think just calling:

sourceuser.save

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

Is that what you were looking for?

-Danimal

Hi,

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, Tiberiu

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.

-Danimal