I have users who belong to a group. I also have a room that belongs to a group. I want to use a has_many through association to link the room and the users as such: class Room < ActiveRecord::Base belongs_to :group has_many :users, :through => :group end The SQL generated for the search is incorrect: SELECT users.* FROM users INNER JOIN group ON users.group_id = groups.id WHERE (groups.group_id = 2) The WHERE clause looks for group_id within the groups table when it should be looking for just id. It uses groups.id in the inner join, so I don''t understand why it is wrong in the WHERE clause. Do I need to specify something? Thanks in advance for any help :-). Chris -- Posted via http://www.ruby-forum.com/.
Chris Rericha wrote:> I have users who belong to a group. I also have a room that belongs to > a group. I want to use a has_many through association to link the room > and the users as such: > > class Room < ActiveRecord::Base > > belongs_to :group > has_many :users, :through => :group > > end > > The SQL generated for the search is incorrect: > > SELECT users.* FROM users INNER JOIN group ON users.group_id = > groups.id WHERE (groups.group_id = 2) > > The WHERE clause looks for group_id within the groups table when it > should be looking for just id. It uses groups.id in the inner join, so > I don''t understand why it is wrong in the WHERE clause. Do I need to > specify something?It could be that you''re trying to use has_many :through in an "unsupported configuration". You can do it where both belongs_to associations are in the join model, or where just one of them is, but you can''t do it where neither is in the join model. What do your tables look like, and your other models? -- Josh Susser http://blog.hasmanythrough.com -- Posted via http://www.ruby-forum.com/.
Chris Rericha
2006-Aug-03 13:28 UTC
[Rails] Re: has_many :through a belongs_to relationship
What I really want to do is have the room know about all of the meetings for all of the users in the group. Here are the tables. table Group { id : int ... } table User { id : int group_id : int ... } table Meeting { id : int user_id : int ... } table Room { id : int group_id : int ... } Here are the active record associations: class Group < ActiveRecord::Base has_one :room has_many :users end class User < ActiveRecord::Base belongs_to :group has_many :meetings end class Room < ActiveRecord::Base belongs_to :group has_many :users, :through => :group has_many :meetings, :through => :users ... end If this is not the proper way to use has_many :through, is there a way to associate users meetings with the room? Thanks for your help! Chris -- Posted via http://www.ruby-forum.com/.