views:

88

answers:

2
class Job < ActiveRecord::Base    
has_many :employments, :dependent => :destroy
has_many :users, :through => :employments

class User < ActiveRecord::Base
has_many :employments 
has_many :jobs, :through => :employments

class Employment < ActiveRecord::Base
belongs_to :job
belongs_to :user  # Employment has an extra attribute of confirmed ( values are 1 or 0)

In my view i am trying to update the confirmed fied from 0 to 1 on user click.

<%= link_to "Confirm Job", :action => :confirmjob, :id => job.id %>

In my job Controller I have

  def confirmjob
@job = Job.find(params[:id])
@job.employments.update_attributes(:confirmed, 1)
flash[:notice] = "Job Confirmed"
 redirect_to :dashboard

end

I am sure this is all wrong but I seem to be guessing when it comes to has_many: through. How would I do update the confirmed field in a joined table?

A: 

Here is a stab at it (not tested):

def confirmjob
  @job = Job.find(params[:id])
  @jobs.employments.each do |e|
    e.update_attributes({:confirmed => 1})
  end
  flash[:notice] = "Job Confirmed"
  redirect_to :dashboard
end
Joel
+1  A: 

I think that a job is assigned to a user by the employment. Thus, updating all employments is not a good idea, as Joel suggests. I would recommend this:

class Employment
  def self.confirm!(job)
    employment = Employment.find(:first, :conditions => { :job_id => job.id } )
    employment.update_attribute(:confirmed, true)
  end
end

from your controller

@job = Job.find(params[:id])
Employment.confirm!(@job)

This implies that one job can only be taken by one user.

Ariejan
I'm not sure if the Employment object already exists, or that it may be nil. If that's the case you might want to extend the `Employment#confirm!` method to handle that as well.
Ariejan
Ariejan, Thanks this worked great. Joel this worked as well except it was updating all the records for that user instead of just for the one job.
Fresh
class Employment def self.confirm!(job) employment = Employment.find(:first, :conditions => { :job_id => job.id } ) employment.update_attribute(:confirmed, true) end endWorks, except that i realize i need to pass the current_user id to it as well.Since my model wont take the session data . How would i get the current_user option to workWhat I need is this.class Employment def self.confirm!(job) employment = Employment.find(:first, :conditions => { :job_id => job.id, :user_id => current_user } )employment.update_attribute(:confirmed, true) end end
Fresh