rails : retrieve data in associated tables
I have 3 tables in my rails app. - User - lnkUserPerson - Person
User has_one Person through lnkUserPerson & Person has_one User through lnkUserPerson.
The lnkUserPerson table contains 3 fields - user_fk which represents the id of the user - person_id, which represents the id of of that user in the Person table - boss_id, which represents the开发者_JAVA技巧 id of the user's boss in the Person table
To retrieve the user's details in the person table, am using: @user.lnkuserperson.person.name.
I would like to know how to retrieve the person details of the user's boss.
I tried using:
@userBoss = Person.find(:first, :conditions => ["id = ?", @user.lnkuserperson.boss_id])
but when am trying to call it in my view, it's giving me an error.
I want to know to retrieve the boss details from the Person table by using the @user object.
User model:
has_one :lnkuserperson
has_one :person, :through => :lnkuserperson, :source=>:person
has_one :boss, :through => :lnkuserperson, :source=>:boss
Person model:
has_one :lnkuserperson
has_one :user, :through => :lnkuserperson
lnkuserperson model:
belongs_to :user
belongs_to :person, :class_name => "Person", :foreign_key => "person_id"
belongs_to :boss, :class_name => "Person", :foreign_key => "boss_id"
So to retrieve the boss details(in the e.g below am retrieving the name) of the user, i just call:
@user.lnkuserperson.boss.name
You should be able to do it through the following means in Rails3 (I'm assuming this is Rails3 as it's tagged that way):
In app/models/user.rb:
# app/models/user.rb
#scope for pulling a specific user via Boss ID
scope :by_boss, lambda { |boss_id| where("id = ?", boss_id) }
In app/models/person.rb
#app/models/person.rb
#scope for finding a person by Boss ID
scope :boss, lamba { |boss_id| joins(:users) & User.by_boss(boss_id) }
In your controller:
def show
@boss = Person.boss(@users.lnkuserperson.boss_id)
end
As an aside instead of doing this:
@user.lnkuserperson.person.name
You can do this from your Person model:
#app/models/person.rb
delegate :name, :to => :lnk_user_person
This gives you an improved method call of: @user.lnkuserperson.name
try the collect method for associated object http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
@author.authorships.collect { |a| a.book }
精彩评论