Ruby on Rails 4.2 '上未定义的方法

webghufk  于 2022-12-26  发布在  Ruby
关注(0)|答案(2)|浏览(134)

我有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

我得到以下错误:未定义#<Port::ActiveRecord_Associations_CollectionProxy:0x007fde543e75d0>的方法terminals
我得到以下错误:
未定义<Country::ActiveRecord_Relation:0x007fde57657b00>的方法ports

dm7nw8vv

dm7nw8vv1#

@country.ports返回端口数组,没有返回终端数组。您应该声明has_many :throughCountry模型的关系。

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

比在控制器处,

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

另见:

  • 导轨导向器
db2dz4w8

db2dz4w82#

@terminals = @country.ports.terminals

此行错误,端口是ActiveRecord数组。您需要执行以下操作

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

相关问题