0

我有两个类 -pop_vlans定义logical_interfaces如下:

逻辑接口.rb

class LogicalInterface < ActiveRecord::Base
  has_many :pop_vlans
end

pop_vlans.rb

class PopVlan < ActiveRecord::Base
  self.table_name = 'pop_vlans'
  belongs_to :logical_interface, :class_name => "LogicalInterface", :foreign_key => "vlan_id"
end

然后在我的控制器中,我试图访问pop_id相关对象的列,pop_vlans但出现未定义的错误:

逻辑接口控制器.rb

def update
  if params[:id]
    @logical_interface = LogicalInterface.find(params[:id]) 

     @pop_id = @logical_interface.pop_vlan.pop_id # error
  end
end

但是,我可以获得我想要的属性,但它需要一些额外的行:

@vlan_id = @logical_interface.vlan_id

@pop_vlan = PopVlan.find(@vlan_id) 

@pop_id = @pop_vlan.pop_id

但我宁愿让我的脚本更简洁一些(另外,找出上面为什么不起作用,因为它真的让我很烦!)。

4

1 回答 1

1

你已经定义

has_many :pop_vlans

这意味着您必须使用

@logical_interface = LogicalInterface.find(...)
@logical_interface.pop_vlans # return an array of pop_vlans
#                          ^

@logical_interface.pop_vlans.map(&:pop_id) # return an array of pop_ids
于 2013-08-15T10:27:00.993 回答