用户/组关系的has_and_belongs_to_many或has_many?

时间:2012-02-03 14:44:16

标签: ruby-on-rails has-and-belongs-to-many has-one

我正在研究具有以下型号的Rails 3.1应用程序:

用户:

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

组:

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

它们之间有一个连接表,而groups表也有一个“user_id”列。我希望能够在我的groups_controller.rb

中写这个
@group = Group.find(params[:id])
foo = @group.owner

但是当我这样做时,我会遇到以下错误:

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

我不明白为什么它甚至在找那个专栏。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

确保您的groups表具有user_id或owner_id列并尝试此操作:

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