多元化的多对多但仍然未初始化的常数

时间:2014-05-17 07:18:45

标签: ruby-on-rails ruby

根据下面我认为这个设置很好:

class Location < ActiveRecord::Base
  has_many :traders
  has_many :servicelocations
  has_many :services, through: :servicelocations
end

class Service < ActiveRecord::Base
    has_many :servicelocations
    has_many :locations, through: :servicelocations
end

class ServiceLocation < ActiveRecord::Base
    belongs_to :location
    belongs_to :service
end

class Trader < ActiveRecord::Base
  belongs_to :location
end

问题是我仍然得到uninitialized constant error

我注意到,当我创建模型ServiceLocation时,funky rails magic创建了service_location.rb,但我不确定是否a)这是问题,b)如果它是如何修复它。

2 个答案:

答案 0 :(得分:1)

我猜ruby明白servicelocations就像一个单词,因此您需要将模型更改为Servicelocation或将关联更改为service_locations。第二种方法我认为更好,它会像:

class Location < ActiveRecord::Base
  has_many :traders
  has_many :service_locations
  has_many :services, through: :service_locations
end

class Service < ActiveRecord::Base
  has_many :service_locations
  has_many :locations, through: :service_locations
end

答案 1 :(得分:1)

我相信你的错误来自于此

class Service < ActiveRecord::Base
    has_many :servicelocations
    has_many :locations, through: :servicelocations
end

这些应该是这样的

class Service < ActiveRecord::Base
    has_many :service_locations
    has_many :locations, through: :service_locations # notice the underscore
end

您的模型类名称为ServiceLocation,其轨道约定名称为service_location而非servicelocation

在这里,你必须改变

class Location < ActiveRecord::Base
  has_many :traders
  has_many :service_locations
  has_many :services, through: :service_locations
end