Reputation: 3696
right now I have a jobs table with
has_many :applicants
has_many:users, through: :applicants
and a applicant table with
belongs_to :job
belongs_to :user
and a user table with
has_many :applicants
has_many:jobs, through: :applicants
So Users are connected through applicant table to Jobs table and vise versa.
I'm not sure I'm updating the model correctly. Right now it looks like this:
def addapply
@job = Job.find(params[:id])
applicant = Applicant.find_or_initialize_by(job_id: @job.id)
applicant.update(user_id: current_user.id)
redirect_to @job
end
But I got to thinking - would not this replace whatever association was there before?
I started looking around and found this in someone else's code:
def update
unless params[:user_relationships][:user_category_ids]
# Set default user category if not selected.
@user.user_category_relationships.build(
:category_id => '1',
:created_by_user_id => @current_user.id,
:name_id => @name.id
)
else
params[:user_relationships][:user_category_ids].each { |user_category_id|
@user.user_category_relationships.build(
:category_id => user_category_id,
:created_by_user_id => @current_user.id,
:name_id => @name.id
)
}
end
end
I'm not sure how that all works but perhaps I do need to iterate through them with a .each before I update.
I don't want to replace what is already there, I just want to add to it.
In Short what is the best way to update (or rather add to) a has_many :through joined table association?
Upvotes: 0
Views: 305
Reputation: 30453
Why not?
def addapply
@job = Job.find(params[:id])
applicant = Applicant.where(job_id: @job.id, user_id: current_user.id).first_or_create
redirect_to @job
end
Upvotes: 1