我有3个表:用户,大学和校园。 他们的模型如下:
class User < ActiveRecord::Base
belongs_to :university
end
class Campus < ActiveRecord::Base
belongs_to :university
end
class University < ActiveRecord::Base
has_many :users, dependent: :destroy
has_many :campuses, dependent: :destroy
end
但是我从大学获得校园协会时遇到了问题。检查一下:
1.9.2p290 :012 > u = University.find(3)
=> #<University id: 3, name: "myuni", email: "uni.com", created_at: "2012-06-04 03:48:59", updated_at: "2012-06-13 03:22:18">
1.9.2p290 :013 > u.users
=> [#<User id: 21, name: "myname", email: "myemail", password: "asdfgh", created_at: "2012-08-10 23:42:40", updated_at: "2012-08-10 23:42:40", university_id: 3>]
1.9.2p290 :014 > u.campus
NoMethodError: undefined method `campus' for #<University:0x000000031c8a10>
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb:392:in `method_m
issing'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.0.10/lib/active_record/attribute_methods.rb:46:in `method_
missing'
from (irb):14
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
from /home/mari/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
这可能是由于校园的多元化,但I haven't been able to fix that either。 所以我尝试了u.campu,u.campuses,u.campues,但我得到了相同的“NoMethodError”。
有什么建议吗?感谢
答案 0 :(得分:0)
似乎在添加:
set_table_name 'campus'
到模型:campus.rb修复它
答案 1 :(得分:0)
语法为u.campuses
或u.campuses.first
我还将表格组织为:
class User < ActiveRecord::Base
belongs_to :campus
end
class Campus < ActiveRecord::Base
has_many :users, dependent: :destroy
belongs_to :university
end
class University < ActiveRecord::Base
has_many :campuses, dependent: :destroy
end