简体   繁体   中英

Trouble with has_many :through => association

Caution: I am a 4 week old at programming. I am having trouble with a has_many :through => relationship between my Neighborhood and Cta_train models.

Here are my models:

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

When I try to do this:

neighborhood.CtaTrains

I get this error:

ActiveRecord::HasManyThroughAssociationNotFoundError (Could not find the association :CtaLocation in model Neighborhood):

I have been slogging through this for several hours now....I have tried many iterations of ideas from stackoverflow....what I show above feels like the closest solution, but obviously still not working. Any thoughts would be appreciated!

I think the problem is that you're not following Rails conventions by using lowercase/underscore for your symbols. Class names have to be CamelCase but you should be doing the following everywhere else:

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

*Update: You should also be using :cta_locations (plural) in your has many through

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM