如何构建has_many:通过Rails中相同模型(用户)之间的关系?

时间:2014-10-10 16:11:54

标签: ruby-on-rails ruby-on-rails-4 many-to-many has-many-through

我想在同一个模型(用户)之间建立多对多的关系。

我有用户模型:

class User < ActiveRecord::Base    
  has_many :broker_clients
  has_many :clients, :through => :broker_clients    
end

和BrokerClient:

class BrokerClients < ActiveRecord::Base
  belongs_to :broker, class_name: "User"
  belongs_to :client, class_name: "User"
end

当我使用rails console并执行以下操作时:

>> User.first.clients
  User Load (0.7ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
NameError: uninitialized constant User::BrokerClient
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/inheritance.rb:125:in `compute_type'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/reflection.rb:178:in `klass'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/reflection.rb:420:in `block in source_reflection'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/reflection.rb:420:in `collect'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/reflection.rb:420:in `source_reflection'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/reflection.rb:557:in `check_validity!'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/associations/association.rb:26:in `initialize'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/associations/has_many_through_association.rb:9:in `initialize'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/associations.rb:157:in `new'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/associations.rb:157:in `association'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-4.0.1/lib/active_record/associations/builder/association.rb:70:in `clients'
    from (irb):4
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/railties-4.0.1/lib/rails/commands/console.rb:90:in `start'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/railties-4.0.1/lib/rails/commands/console.rb:9:in `start'
    from /Users/info/.rvm/gems/ruby-2.0.0-p451/gems/railties-4.0.1/lib/rails/commands.rb:62:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'>>

我在这里做错了以获得此错误:

NameError: uninitialized constant User::BrokerClient

1 个答案:

答案 0 :(得分:2)

试试这个:

class User < ActiveRecord::Base    
  has_many :broker_clients, :class_name => "User", :foreign_key => "broker_id"
  has_many :clients, :class_name => "User", :foreign_key => "client_id"

  #Your class definition here...
end

通过以下方式访问客户端和broker_clients:

   clients =  User.first.clients
   broker_clients = User.first.broker_clients