开发者

Rails has_many :through and has_one :through associations

First I'm using Rails 3.1 from the 3-1-stable branch updated an hour ago.

I'm developing an application where I have 3 essential models User, Company and Job, Here's the relevant part of the models:

class User < ActiveRecord::Base
  has_many :companies_users, class_name: "CompaniesUsers"
  has_many :companies, :through => :companies_users, :source => :company
end

class Company < ActiveRecord::Base
  has_many :companies_users, class_name: "CompaniesUsers"
  has_many :employees, :through => :companies_users, :source => :user
  has_many :jobs, :dependent => :destroy
end

class Job < ActiveRecord::Base
  belongs_to :company, :counter_cache =&g开发者_Go百科t; true
end

class CompaniesUsers < ActiveRecord::Base
  belongs_to :company
  belongs_to :user
end

The code works just fine, but I have been wondering if it's possible to:

I want to link a job with an employer, so think of this scenario: A user John who's an employee at Example, he posted the job Rails Developer, so I want to access @job.employer and it should get me back the user John, in other words:

@user = User.find_by_name('john')
@job   = Job.find(1)
@job.employer == @user       #=> true

So I thought of two possible solutions

First solution

class Job
  has_one :employer, :through => :employers
end

class User
  has_many :jobs, :through => :employers
end

class Employer
  belongs_to :job
  belongs_to :user
end

Second solution

class Job
  has_one :employer, :class_name => "User"
end

class User
  belongs_to :job
end

Which route should I go? Is my code right ?

I have another question, how to get rid of the class_name => "CompaniesUsers" option passed to has_many, should the class be Singular or Plural ? Should I rename it to something like Employees ?

P.S: I posted the same question to Ruby on Rails: Talk


Unless I'm missing something, I'd suggest simply doing

class Job
  belongs_to :employer, :class_name => "User"
end

class User
  has_many :jobs
end

This would give you methods like

user = User.first
user.jobs.create(params)
user.jobs # array
job = user.jobs.first
job.employer == user # true

You'll need an employer_id integer field in your Jobs table for this to work.


Typically you want to name your pass through model:

company_user

Then you don't need this:

class_name: "CompaniesUsers"

Just make sure the name of your database table is:

company_users

What you have works for you, so that's great. I just find when I don't follow convention I run in to trouble down the road.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜