has_many :through and has_one :through associations

25 views
Skip to first unread message

Wael Nasreddine

unread,
Jun 22, 2011, 4:50:52 AM6/22/11
to rubyonra...@googlegroups.com
Hello,

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 => 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 Stackoverflow

-- 
Wael Nasreddine: Design & Coding at TechnoGate
contact | wael.na...@gmail.com - +33.6.31.17.41.10 | skype - eMxyzptlk

PGP.sig
Reply all
Reply to author
Forward
0 new messages