2012-10-01 93 views
1

我使用Rails 2.3,我有3個表,它管理用戶對建築物的權限。 mygroups表是用戶和建築物所屬的組的列表。 mygroupsbuildings是與其關聯組的建築物列表。 mygroupsusers是具有關聯組的用戶列表。Rais has_many&通過查詢

create_table "mygroups", :force => true do |t| 
    t.string "name" 
    t.integer "user_id" 
    t.string "user_name" 
    t.integer "permissions" 
end 

create_table "mygroupbuildings", :force => true do |t| 
    t.integer "mygroup_id" 
    t.integer "building_id" 
end 

create_table "mygroupusers", :force => true do |t| 
    t.integer "mygroup_id" 
    t.integer "user_id" 
    t.string "user_name" 
end 

我想創建發現如果特定user_id是作爲特定building_id同一組的成員的查詢。

我已經安裝了以下關聯:

class Mygroup < ActiveRecord::Base 
    has_many :mygroupusers 
    has_many :mygroupbuildings 
end 

class Mygroubuilding < ActiveRecord::Base 
    belongs_to :mygroup 
    has_many :mygroupusers, :through => :mygroup 
end 

class Mygroupuser < ActiveRecord::Base 
    belongs_to :mygroup 
    has_many :mygroupbuildings, :through => :mygroup 
end 

我寫了下面的查詢:

Mygroupuser.find(:all, 
       :include => :mygroupbuildings, 
       :select => "mygroupbuildings.building_id, mygroupusers.user_id", 
       :conditions => ["mygroupbuildings.building_id = '#{building.id}' AND mygroupusers.user_id = '#{current_user.user_id}'"])  

這給我下面的錯誤:

的ActiveRecord :: StatementInvalid(mysql的::錯誤:'on子句'中的未知列'mygroups.mygroup_id':SELECT mygroupusersid AS t0_r0,mygroupusersmygroup_id AS t0_r1,mygroupusersuser_id AS t0_r2,mygroupusersuser_name AS t0_r3,mygroupuserscreated_at AS t0_r4,mygroupusersupdated_at AS t0_r5,mygroupbuildingsid AS t1_r0,mygroupbuildingsmygroup_id AS t1_r1,mygroupbuildingscoursewalk_id AS t1_r2,mygroupbuildingscreated_at AS t1_r3,mygroupbuildingsupdated_at AS t1_r4 FROM mygroupusers LEFT OUTER JOIN mygroups ON(mygroupusersid = mygroupsmygroup_id)LEFT OUTER JOIN mygroupbuildings ON(mygroupbuildingsmygroup_id = mygroupsid)WHERE(mygroupbuildings.building_id = '2' 和mygroupusers.user_id = '55' )):

感謝,

尼克,

回答

0

這是查詢需要如何設置,返回包含查詢USER_ID和building_id組:

Mygroup.find(:all, 
      :include => [:mygroupbuildings, :mygroupusers], 
      :conditions => ["mygroupbuildings.building_id = #{building.id} AND mygroupusers.user_id = #{current_user.user_id}"])