Ruby on rails RubyonRails 4.2上的未定义方法`

Ruby on rails RubyonRails 4.2上的未定义方法`,ruby-on-rails,ruby,methods,undefined,Ruby On Rails,Ruby,Methods,Undefined,这是我第一次在这里问问题。我知道我一定错过了一些非常琐碎的东西,但我已经有一段时间没能把它整理好了。我不熟悉rails 我有4类,码头属于港口,港口属于国家,国家属于地区 class Region < ActiveRecord::Base has_many :countries end class Country < ActiveRecord::Base belongs_to :region has_many :ports end class Port <

这是我第一次在这里问问题。我知道我一定错过了一些非常琐碎的东西,但我已经有一段时间没能把它整理好了。我不熟悉rails

我有4类,码头属于港口,港口属于国家,国家属于地区

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
类区域
我正在尝试运行以下代码:

class TerminalsController < ApplicationController
    def index    
        @country = Country.find_by name: 'Pakistan'
        @terminals = @country.ports.terminals
    end
end
class TerminalsController
我发现以下错误:
#

我发现以下错误:

谢谢你的帮助

干杯

塔哈

此行错误,端口为ActiveRecord数组。 你需要这样做

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

@country.port
返回端口数组,不返回终端数组。您应该声明
国家
车型有很多关系

class Country < ActiveRecord::Base
  belongs_to :region
  has_many :ports
  has_many :terminals, through: :ports
end
class Country
而不是在控制器上

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

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