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)的屬性。有任何想法嗎?
謝謝您的回答。我試過了,但得到一個錯誤: Mysql ::錯誤:'where子句'中的未知列'preferred_categories.category_id':SELECT * FROM'users' WHERE('preferred_categories'.'category_id' IN(4)) – hebe
似乎很奇怪。也許這是Rails 2.3和2.2之間的區別。也許嘗試明確指定連接...看到我更新的答案 –
FTW,它現在與更新的版本。今天浪費了4個小時,應該早點提問..謝謝! – hebe