2011-10-12 81 views
0

當我連接兩個表(rails 2.2.2)時,rails僅返回應用了find_by方法的模型中的屬性值:rails:無法從連接表中獲取屬性

關係:

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 

=>結果:我從用戶表僅屬性。

我需要的是來自其他表(preferred_categories,company_infos)的屬性。有任何想法嗎?

回答

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

UPDATE 嘗試指定連接明確

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

謝謝您的回答。我試過了,但得到一個錯誤: Mysql ::錯誤:'where子句'中的未知列'preferred_categories.category_id':SELECT * FROM'users' WHERE('preferred_categories'.'category_id' IN(4)) – hebe

+0

似乎很奇怪。也許這是Rails 2.3和2.2之間的區別。也許嘗試明確指定連接...看到我更新的答案 –

+0

FTW,它現在與更新的版本。今天浪費了4個小時,應該早點提問..謝謝! – hebe