【问题标题】:Trouble with has_many :through => associationhas_many 的问题:通过 => 关联
【发布时间】:2011-12-19 00:19:18
【问题描述】:

注意:我是 4 周大的编程人员。我的 Neighborhood 和 Cta_train 模型之间的 has_many :through => 关系有问题。

这是我的模型:

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(在模型 Neighborhood 中找不到关联 :CtaLocation):

我已经为此苦苦挣扎了几个小时......我已经尝试了许多来自stackoverflow的想法迭代......我上面展示的感觉像是最接近的解决方案,但显然仍然无法正常工作。任何想法将不胜感激!

【问题讨论】:

    标签: ruby-on-rails activerecord has-many-through


    【解决方案1】:

    我认为问题在于您没有通过使用小写/下划线作为符号来遵循 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
    

    *更新:你还应该在你的 has many through 中使用 :cta_locations(复数)

    【讨论】:

    • 是的!你的更新成功了。我有 :CtaLocations 并且它有效。我不知道该命名约定该说什么……当我更改为小写/下划线时,它会因未定义的方法而中断。谢谢!!
    • 很高兴为您工作。不确定未定义的方法,但我强烈建议您遵循标准约定,特别是如果您计划与其他 Rails 开发人员一起开展该项目。 Rails 指南很棒并且使用了这些约定:guides.rubyonrails.org/association_basics.html
    • 我已尝试修复命名约定,但遇到了一些问题。我提出了一个关于命名约定的新问题,以防其他人遇到类似问题:stackoverflow.com/questions/8553768/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多