警告:我是一个4周大的编程人员。我在使用has_many时遇到问题:通过=>我的邻居和Cta_train模特之间的关系。
以下是我的模特:
class CtaTrain < ActiveRecord::Base
belongs_to :Ctaline
has_and_belongs_to_many :searches
has_many :neighborhoods, :through => :CtaLocation, :foreign_key => :neighborhood_id
has_many :CtaLocations
end
class Neighborhood < ActiveRecord::Base
has_many :geopoints
has_many :listings
has_many :properties
has_and_belongs_to_many :searches
has_many :CtaTrains, :through => :CtaLocation, :foreign_key => :cta_train_id
has_many :CtaLocations
end
class CtaLocation < ActiveRecord::Base
belongs_to :neighborhood
belongs_to :CtaTrain
end
当我尝试这样做时:
neighborhood.CtaTrains
我收到此错误:
ActiveRecord :: HasManyThroughAssociationNotFoundError(找不到关联:模型邻域中的CtaLocation):
我已经在这几个小时内搞砸了....我已经尝试了很多来自stackoverflow的想法迭代....我上面显示的感觉就像是最接近的解决方案,但显然仍然无法正常工作。任何想法都将不胜感激!
答案 0 :(得分:2)
我认为问题在于您没有通过对符号使用小写/下划线来遵循Rails约定。类名必须是CamelCase,但您应该在其他地方执行以下操作:
class CtaTrain < ActiveRecord::Base
belongs_to :cta_line
has_and_belongs_to_many :searches
has_many :neighborhoods, :through => :cta_locations, :foreign_key => :neighborhood_id
has_many :cta_locations
end
*更新:您还应该使用:cta_locations(复数)在您有很多通过