views:

183

answers:

1

Hi all,

I'm having problems adding to a Has Many Through association using user_ids.

My communication model looks like this:

class communication
 has_many :recipients
 has_many :users, :through => :recipients
end

In my create action for the communication controller I am trying to manually add user_ids to the communication object like so:

@communication = new Communications(params[:communication])
@communication.user_ids << id
logger.debug @communication.user_ids # is empty

I can't work out why @communication.user_ids array is empty, even when I do a hard coded id like so:

@communication = new Communications(params[:communication])
@communication.user_ids << 1
logger.debug @communication.user_ids # is still empty!

I'm still getting an empty @communication.user_ids array.

Am I missing something with my method? Any tips to get this working?

Thanks in advance!

+2  A: 

Since it's a has_many :through, maybe you need to supply full objects so that the relationship can be created smoothly. Try this:

@communication = Communication.new params[:communication]
@communication.users << User.find( 1 )
@communication.user_ids  # should be [ 1 ]
austinfromboston