我的模型结构是:
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
class ServiceLocation < ActiveRecord::Base
belongs_to :location
belongs_to :service
end
执行
时出现以下错误s=Service.find(1)
l=Location.find(1)
s.service_locations << l
ActiveRecord::AssociationTypeMismatch: ServiceLocation(#84843750) expected, got Location(#93937750)
当变量反转并且我在这里找不到问题时,也会发生这种情况,还有什么想法?
答案 0 :(得分:0)
正确的代码将是以下之一:
l=Location.find(1)
s.locations << l
或
l=ServiceLocation.find(1)
s.service_locations << l
这是自我解释,我希望你得到错误。另请查看documentation,它将帮助您了解ActiveRecord关联。