Taha Zuberi
Taha Zuberi

Reputation: 23

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>

Upvotes: 2

Views: 178

Answers (2)

Masudul
Masudul

Reputation: 21961

@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:

Upvotes: 3

IcyBright
IcyBright

Reputation: 664

@terminals = @country.ports.terminals

This line is wrong, ports is ActiveRecord Array. You would need to do

@country.ports.terminals.each do |terminal|
  puts terminal.ports
end

Upvotes: 0

Related Questions