开发者

Rails model association - users create jobs but then users should accept jobs and get assigned to them

Right now I have a model where users can login and create jobs. Jobs belongs_to :users and user has_many :jobs. So far so good. But now I want to set up a one-to-one relationship where each JOB can have one user assigned to them. What is the best way to associate the user model and jobs model?

Examples:

  1. User can create jobs and a different user gets assigned to it.
  2. User can create jobs and assign him/herself to it.
  3. Jobs can have no more than one user assigned,开发者_如何转开发 but is not required to have an assigned user.
  4. Jobs will always have a creator (user_id).

Since I've already set up jobs belongs_to :users, there's already a user_id column for jobs so how would I re-use that to now show accepting the job / getting assigned to the job?

Thanks!


You can set multiple associations between your Job and User classes using different foreign keys:

class Job < ActiveRecord::Base
  belongs_to :user
  belongs_to :assigned_user, :class_name => "User", :foreign_key => "assigned_user_id"
end

class User < ActiveRecord::Base
  has_many :jobs
  has_many :assigned_jobs, :class_name => "Job", :foreign_key => "assigned_user_id"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜