无法访问Rails中的外键属性

时间:2013-08-15 10:20:11

标签: ruby-on-rails ruby ruby-on-rails-2

我有两个类 - pop_vlanslogical_interfaces定义如下:

logical_interface.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列,但我收到一个未定义的错误:

logical_interface_controller.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

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

1 个答案:

答案 0 :(得分: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