Rails has_many&通过查询

时间:2012-10-01 21:16:16

标签: ruby-on-rails has-many-through

我正在使用Rails 2.3,我有3个表,用于管理建筑物的用户权限。 mygroups表是用户和建筑物所属的组列表。 mygroupsbuildings是具有相关组的建筑物列表。 mygroupsusers是具有关联组的用户列表。

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,mygroupusers。{{1 AS t0_r1,mygroup_idmygroupusers AS t0_r2,user_idmygroupusers AS t0_r3,user_namemygroupusers AS t0_r4,{{1 } {。{1}} AS t0_r5,created_atmygroupusers AS t1_r0,updated_atmygroupbuildings AS t1_r1,idmygroupbuildings AS t1_r2,mygroup_idmygroupbuildings AS t1_r3,coursewalk_idmygroupbuildings AS t1_r4 FROM created_at LEFT OUTER JOIN mygroupbuildings ON({{1} }。updated_at = mygroupusersmygroups)LEFT OUTER JOIN mygroupusers ON(idmygroups = mygroup_id。{{ 1}})WHERE(mygroupbuildings.building_id ='2'和mygroupusers.user_id = '55')):

谢谢,

尼克,

1 个答案:

答案 0 :(得分: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}"])