rails:无法从连接表中获取属性

时间:2011-10-12 19:19:52

标签: mysql ruby-on-rails

当我连接两个表(rails 2.2.2)时,rails只返回应用了find_by方法的Model的属性值:

关系:

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

查询:

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

=&GT;结果:我只从users表中获取属性。

我需要的是其他表格中的属性(preferred_categories,company_infos)。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在您的情况下,我认为ActiveRecord可以处理您的查询。您应该使用include急切加载所需的关联。

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

然后在相关模型上访问您需要的属性:

# 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_)

<强>更新 尝试明确指定联接

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