1

我使用的是 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::Error: Unknown column 'mygroups.mygroup_id' in 'on Clause': SELECT mygroupusers. idAS t0_r0, mygroupusers. mygroup_idAS t0_r1, mygroupusers. user_idAS t0_r2, mygroupusers. user_nameAS t0_r3, mygroupusers. created_atAS t0_r4, mygroupusers. updated_atAS t0_r5, mygroupbuildings. idAS t1_r0, mygroupbuildings. mygroup_idAS t1_r1, mygroupbuildings. coursewalk_idAS t1_r2, mygroupbuildings. created_atAS t1_r3, . mygroupbuildingsAS updated_att1_r4 从左外连接打开 ( . = . ) 左外连接打开 ( . = . ) WHERE (mygroupbuildings.building_id = '2' AND mygroupusers.user_id = '55')):mygroupusersmygroupsmygroupusersidmygroupsmygroup_idmygroupbuildingsmygroupbuildingsmygroup_idmygroupsid

谢谢,

缺口,

4

1 回答 1

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}"])      
于 2012-10-01T23:20:44.077 回答