Search code examples
ruby-on-railsrubymethodsundefined

undefined method on Ruby on Rails 4.2`


I have 4 classes, Terminal belongs_to Port, Ports belong to_Country and Countries belong_to Region.

class Region < ActiveRecord::Base
    has_many :countries
end  

class Country < ActiveRecord::Base
  belongs_to :region
  has_many :ports
end

class Port < ActiveRecord::Base
  belongs_to :country
  has_many :terminals
end

class Terminal < ActiveRecord::Base
  belongs_to :port
end

I'm trying to run following code:

class TerminalsController < ApplicationController
    def index    
        @country = Country.find_by name: 'Pakistan'
        @terminals = @country.ports.terminals
    end
end

I get following error: undefined method terminals for #<Port::ActiveRecord_Associations_CollectionProxy:0x007fde543e75d0>

I Get following error:

undefined method ports for <Country::ActiveRecord_Relation:0x007fde57657b00>


Solution

  • @country.ports return array of ports, no terminals array is returned. You should declare has_many :through relation to Country model.

    class Country < ActiveRecord::Base
      belongs_to :region
      has_many :ports
      has_many :terminals, through: :ports
    end
    

    Than at controller,

    class TerminalsController < ApplicationController
        def index    
            @country = Country.find_by name: 'Pakistan'
            @terminals = @country.terminals # Don't need intermediate ports
        end
    end
    

    See also: