我想在同一個模型(用戶)之間建立多對多的關係。如何構建has_many:通過Rails中相同模型(用戶)之間的關係?
我有用戶模式:
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
當我使用的軌道控制檯,這樣做:
>> 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
在你的經紀人的客戶採取一看,它並沒有太大的意義。它通常是'belongs_to:broker,class_name:'User''和'belongs_to:client,class_name:'User''。然後'用戶'將'has_many:客戶端,通過::broker_clients'。 – ptd 2014-10-10 16:34:10
那麼,Client和Broker是User的子類。我修改了BrokerClient:class BrokerClients
2014-10-10 16:45:17
你的班級應該是單數。如果你的表是'broker_clients',那麼'class BrokerClient'。 ActiveRecord根據你的表名尋找合適的類,它不存在。 – ptd 2014-10-10 16:51:30