【问题标题】:undefined method on Ruby on Rails 4.2`Ruby on Rails 4.2 上的未定义方法
【发布时间】:2015-05-20 06:38:47
【问题描述】:

这是我第一次在这里提问。我知道我必须在这里遗漏一些非常微不足道的东西,但现在已经有一段时间无法解决了。我是 Rails 新手。

我有 4 个类,Terminal belongs_to Port,Ports belongs to_Country 和国家 belongs_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

我正在尝试运行以下代码:

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

我收到以下错误: 未定义的方法terminals#&lt;Port::ActiveRecord_Associations_CollectionProxy:0x007fde543e75d0&gt;

我得到以下错误:

未定义方法ports 用于&lt;Country::ActiveRecord_Relation:0x007fde57657b00&gt;

感谢您的帮助。

干杯,

塔哈

【问题讨论】:

    标签: ruby-on-rails ruby methods undefined


    【解决方案1】:
    @terminals = @country.ports.terminals
    

    这一行是错误的,ports 是 ActiveRecord Array。 你需要这样做

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

    【讨论】:

      【解决方案2】:

      @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
      

      另请参阅:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 2016-12-15
        • 2019-10-31
        • 2018-07-06
        • 2012-09-25
        相关资源
        最近更新 更多