3

I'm working on a Rails 3.1 app that has the following models:

User:

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :ownerships, :class_name => 'Group'
end

Group:

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_one :owner, :class_name => 'User'
end

There's a join table between them, and the groups table also has a "user_id" column. I would expect to be able to write this in my groups_controller.rb

@group = Group.find(params[:id])
foo = @group.owner

but when I do I'm presented with the following error:

Mysql2::Error: Unknown column 'users.group_id' in 'where clause': SELECT  `users`.* FROM `users`  WHERE `users`.`group_id` = 1 LIMIT 1

I don't understand why it's even looking for that column. Any help would be appreciated!

Steve Davis
  • 959
  • 1
  • 11
  • 25

1 Answers1

2

make sure your groups table has a user_id or owner_id column and try this:

  class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    belongs_to :owner, :class_name => 'User'
  end
antpaw
  • 15,444
  • 11
  • 59
  • 88
  • Thanks antpaw. This seems to be a step forward (as it's not giving me MySQL errors any more), but it's still returning nil for @group.owner.inspect. – Steve Davis Feb 03 '12 at 14:57
  • are you sure that column owner_id is not empty and the user with that id lives in the user table? – antpaw Feb 03 '12 at 15:09
  • You're right! I actually had "user_id" instead of "owner_id." BUT now when I try to come in from the other side (@user.ownerships.inspect) it's looking for the column "user_id" again. P.S. I updated my User model in the original question. – Steve Davis Feb 03 '12 at 15:15
  • maybe adding :foreign_key option will help, sorry im not sure – antpaw Feb 04 '12 at 12:13
  • That was it exactly! Thanks so much! :) – Steve Davis Feb 04 '12 at 16:32