has_and_belongs_to_many或has_many对于用户/组的关系? [英] has_and_belongs_to_many or has_many for user/group relationship?

查看:104
本文介绍了has_and_belongs_to_many或has_many对于用户/组的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有以下模型的Rails 3.1应用程序:

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

用户:

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

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!

推荐答案

确保您的groups表具有user_id或owner_id列,然后尝试以下操作:

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

这篇关于has_and_belongs_to_many或has_many对于用户/组的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆