我在轨道3.2.14上有ruby的项目。我有2个名为“countries”和“users”的表。在“users”表中,FK名为“countries_id”。
在模型上我有表关系,如:
在countries.rb
我设置了关系:
class Countries < ActiveRecord::Base
self.primary_key = "id"
has_many :users, :dependent => :destroy # plural
end
,在users.rb中,如:
class Users < ActiveRecord::Base
self.primary_key = "id"
belongs_to :countries,
:class_name => "Countries",
:foreign_key => "countries_id"
end
当我想检查复数关系时,它没有.. 我输入rails console命令,如下所示
c=Countries.find_by_id(1)
然后当我输入命令u=c.users
时,我有一些错误
错误:
c=Countries.find_by_id(1)
Countries Load (0.3ms) SELECT `countries`.* FROM `countries` WHERE `countries`.`id` = 1 LIMIT 1
=> #<Countries id: 1, code: "IND", name: "Indonesia", created_at: "2014-02-17 09:18:11", updated_at: "2014-02-17 09:18:11">
1.9.3-p484 :012 > u=c.users
NameError: uninitialized constant Countries::User
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/inheritance.rb:111:in `compute_type'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/reflection.rb:172:in `klass'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/association.rb:118:in `klass'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/association.rb:171:in `find_target?'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_association.rb:334:in `load_target'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_proxy.rb:44:in `load_target'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_proxy.rb:87:in `method_missing'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands/console.rb:47:in `start'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands/console.rb:8:in `start'
from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
1.9.3-p484 :013 > ^C
1.9.3-p484 :013 >
我知道我的问题真的让人跳了起来
无论如何,谢谢你,抱歉我的英语不好:)
答案 0 :(得分:3)
您应该在代码中更改很多内容:
应用/模型/ country.rb 强>
class Country < ActiveRecord::Base
has_many :users, :dependent => :destroy
end
应用/模型/ user.rb 强>
class Users < ActiveRecord::Base
belongs_to :country,
:foreign_key => "countries_id"
end
并像这样使用它:
country = Country.find(1)
p country.users
答案 1 :(得分:0)
问题是Rails Active Record
模型不能多个。您创建了具有复数的模型,因此将它们更改为单数或更好的方法是使用单数名称再次创建它们。
Countries
应为Country
,Users
应为User
。
有关命名约定的详细信息,请参阅This。
希望它有所帮助!