2011-12-18 95 views
0

注意:我是一个4周的编程。我在邻居和Cta_train模型之间的has_many:through =>关系遇到问题。has_many问题:通过=>关联

这里是我的模型:

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 (Could not find the association :CtaLocation in model Neighborhood):

我已经通过这个苦读几现在小时....我已经尝试了很多来自stackoverflow的想法迭代....我上面显示的感觉就像最接近的解决方案,埠显然仍然不起作用。任何想法,将不胜感激!

回答

2

我认为问题在于你没有遵循Rails约定,使用小写/下划线作为符号。类名必须首字母大写,但你应该做以下的其他地方:

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(复数)您有许多通过

+0

YES!你的更新诀窍。我有:CtaLocations和它的作品。我不知道该怎么说命名约定....当我改变成小写/下划线它打破了未定义的方法。谢谢!! – tbone 2011-12-18 16:41:15

+0

很高兴为你工作。不确定未定义的方法,但我强烈建议遵循标准约定,特别是如果您计划与其他Rails开发人员一起处理项目。 Rails指南非常棒,并使用这些约定:http://guides.rubyonrails.org/association_basics.html – 2011-12-18 17:11:31

+0

我试图修复命名约定,我遇到了一些问题。我开始了一个关于命名约定的新问题,以防其他人遇到类似问题:http://stackoverflow.com/questions/8553768/trouble-with-rails-naming-conventions – tbone 2011-12-18 18:30:05