Rails联结表名称错误

时间:2014-09-06 14:09:48

标签: ruby-on-rails

我正在尝试使用联结表。 我有三个模型:Professional,Skill和交叉参考表ProfessionalsSkills。

专业模特

class Professional < ActiveRecord::Base
    has_many :professionals_skills
    has_many :skills, :through => :professionals_skills
end

技能模型

class Skill < ActiveRecord::Base
    has_many :professionals_skills
    has_many :professionals, :through => :professionals_skills
end

交叉参考表

class ProfessionalsSkills < ActiveRecord::Base
    belongs_to :professional
    belongs_to :skill
end

在Rails控制台中

irb(main):005:0* @x = Professional.find(1)
  Professional Load (0.1ms)  SELECT  "professionals".* FROM "professionals"  WHERE "professionals"."id" = ? LIMIT 1  [["id", 1]]
=> #<Professional id: 1, gender: 1, first_name: "Goofy", last_name: "Muff", date_of_birth: "1985-07-20 00:00:00", email_address: "example@example.com", city_id: 1, created_at: "2014-09-06 13:04:57", updated_at: "2014-09-06 13:04:57">
irb(main):006:0>

但......当我尝试时:

@x.skills

NameError: uninitialized constant Professional::ProfessionalsSkill
    from /Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.5/lib/active_record/inheritance.rb:133:in `compute_type'
    from /Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.5/lib/active_record/reflection.rb:221:in `klass'...

我做错了什么?我正在使用Rails 4.1.4

1 个答案:

答案 0 :(得分:2)

如果仔细观察它所说的错误

,那么模型应该是单数形式的
NameError: uninitialized constant Professional::ProfessionalsSkill

请注意ProfessionalsSkill而不是ProfessionalsSkills

您需要将模型重命名为单数形式,以及表格,以匹配导轨约定。