开发者

rails: can't get the attributes from the joined table

When I join two tables (rails 2.2.2), then rails开发者_如何学运维 only returns the values of the attributes from the Model for which the find_by method is applied:

Relations:

class User < ActiveRecord::Base
  ..
  has_one  :company_info, :dependent => :destroy
  has_many :preferred_categories, :dependent => :destroy
end


class PreferredCategory < ActiveRecord::Base
  ..
  belongs_to :user
  belongs_to :category

end


class Category < ActiveRecord::Base
  ..
  has_many :preferred_categories, :dependent => :destroy
  has_many :users, :through => :preferred_categories
end


class CompanyInfo < ActiveRecord::Base
  ..
  belongs_to :user 
end

Query:

class Category < ActiveRecord::Base
  ..
  def total_tradesmen   #returns tradesmen with a certain skill-profile
  a = self.self_and_all_children_for.collect {|cat| cat.id}
  total_tradesmen = User.find_by_sql(
    "select *
    from users u
    inner join preferred_categories pc on pc.user_id = u.id
    inner join company_infos ci on ci.user_id = pc.user_id
    where pc.category_id in ( #{a.join(',')} )"
  )
  end
..
end

=> Result: I get only attributes from the users table.

What I need are the attributes from the other tables (preferred_categories, company_infos) as well. Any ideas?


In your case I think that ActiveRecord can handle your query. You should eager load the associations that you need by using include.

total_tradesmen = User.all(
  :include => [:company_info, :preferred_categories],
  :conditions => {:preferred_categories => {:category_id => a}}
)

Then access the attributes you need on the associated models:

# Examples since I don't know the attributes on your models
company_address = total_tradesmen.first.company_info._address_
preferred_category_names = total_tradesmen.first.preferred_categories.map(&:_name_)

UPDATE Try specifying joins explicitly

total_tradesmen = User.all(
  :include => [:company_info, :preferred_categories],
  :joins => [:company_info, :preferred_categories],
  :conditions => {:preferred_categories => {:category_id => a}}
)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜