简体   繁体   中英

undefined method on Ruby on Rails 4.2`

Its my first time asking a question here. I know i must be missing something very trivial here but have been unable to sort it out for a while now. I'm new to rails.

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>

Thanks for the help.

cheerz,

Taha

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

@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

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