我有 4 个类,Terminal belongs_to Port,Ports belongs to_Country 和 Countries 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
对于 #<Port::ActiveRecord_Associations_CollectionProxy:0x007fde543e75d0>
我得到以下错误:
未定义的方法 ports
对于 <Country::ActiveRecord_Relation:0x007fde57657b00>
最佳答案
@country.ports
返回端口数组,不返回终端数组。您应该声明 has_many :through
与 Country
模型的关系。
class Country < ActiveRecord::Base
belongs_to :region
has_many :ports
has_many :terminals, through: :ports
end
比 Controller ,
class TerminalsController < ApplicationController
def index
@country = Country.find_by name: 'Pakistan'
@terminals = @country.terminals # Don't need intermediate ports
end
end
另请参阅:
关于ruby-on-rails - Ruby on Rails 4.2` 上的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105788/