0

我有 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>'

这可能是由于校园的多元化,但我也无法解决这个问题。所以我尝试了 u.campu、u.campuses、u.campues,但我得到了相同的“NoMethodError”。

有什么建议么?谢谢

4

2 回答 2

0

似乎添加:

  set_table_name 'campus'

模型:campus.rb 修复它

于 2012-08-14T03:59:21.230 回答
0

语法是u.campusesu.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
于 2012-08-14T04:07:18.730 回答