Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top