Rais has_many & through query-Collection of common programming errors
I’m using Rails 2.3 and I have 3 tables, which manages user permissions to buildings. The mygroups table is the list of groups users and buildings belong to. The mygroupsbuildings is the list of buildings with their associated group. The mygroupsusers is the list of users with their associated group.
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
I would like to create a query that finds out if a particular user_id is a member of the same group as a particular building_id.
I have setup the following associations:
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
I wrote the following query:
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}'"])
This give me the following error:
ActiveRecord::StatementInvalid (Mysql::Error: Unknown column ‘mygroups.mygroup_id’ in ‘on clause’: SELECT mygroupusers
.id
AS t0_r0, mygroupusers
.mygroup_id
AS t0_r1, mygroupusers
.user_id
AS t0_r2, mygroupusers
.user_name
AS t0_r3, mygroupusers
.created_at
AS t0_r4, mygroupusers
.updated_at
AS t0_r5, mygroupbuildings
.id
AS t1_r0, mygroupbuildings
.mygroup_id
AS t1_r1, mygroupbuildings
.coursewalk_id
AS t1_r2, mygroupbuildings
.created_at
AS t1_r3, mygroupbuildings
.updated_at
AS t1_r4 FROM mygroupusers
LEFT OUTER JOIN mygroups
ON (mygroupusers
.id
= mygroups
.mygroup_id
) LEFT OUTER JOIN mygroupbuildings
ON (mygroupbuildings
.mygroup_id
= mygroups
.id
) WHERE (mygroupbuildings.building_id = ‘2’ AND mygroupusers.user_id = ’55’) ):
Thanks,
Nick,
-
This is how the query needs to be setup to return the group that contains the queried user_id and building_id:
Mygroup.find(:all, :include => [:mygroupbuildings, :mygroupusers], :conditions => ["mygroupbuildings.building_id = #{building.id} AND mygroupusers.user_id = #{current_user.user_id}"])
Originally posted 2013-11-10 00:11:29.