问题
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!
回答1:
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
来源:https://stackoverflow.com/questions/9130445/has-and-belongs-to-many-or-has-many-for-user-group-relationship