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)
<%= link_to "Confirm Job", :action => :confirmjob, :id => job.id %>
def confirmjob
@job = Job.find(params[:id])
@job.employments.update_attributes(:confirmed, 1)
flash[:notice] = "Job Confirmed"
redirect_to :dashboard
end
我确信这一切都是错的,但我似乎在猜测has_many:通过。 如何更新已连接表中的已确认字段?
答案 0 :(得分:2)
我认为就业分配给用户。因此,正如乔尔所说,更新所有就业并不是一个好主意。我会推荐这个:
class Employment
def self.confirm!(job)
employment = Employment.find(:first, :conditions => { :job_id => job.id } )
employment.update_attribute(:confirmed, true)
end
end
来自您的控制器
@job = Job.find(params[:id])
Employment.confirm!(@job)
这意味着一个作业只能由一个用户执行。
答案 1 :(得分:0)
这是对它的攻击(未经测试):
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