tomb
tomb

Reputation: 1436

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!

Upvotes: 0

Views: 992

Answers (1)

Peter Brown
Peter Brown

Reputation: 51697

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

Upvotes: 2

Related Questions