has_and_belongs_to_many or has_many for user/group relationship?

末鹿安然 提交于 2020-01-01 03:37:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!