Reputation: 11042
I have two classes - pop_vlans
and logical_interfaces
defined as follows:
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
Then in my controller I am trying to access the pop_id
column of the related pop_vlans
object but I get an undefined error:
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
However, I can get the property I want but it requires a few extra lines:
@vlan_id = @logical_interface.vlan_id
@pop_vlan = PopVlan.find(@vlan_id)
@pop_id = @pop_vlan.pop_id
but I'd rather make my scripts a bit more concise (plus, find out why the above doesn't work aswell as it's genuinely annoying me!).
Upvotes: 0
Views: 71
Reputation: 17631
You have define
has_many :pop_vlans
which means you must access it with
@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
Upvotes: 1