Question

What I have:

class Map < ActiveRecord::Base
    has_many :connections
end

this works fine. I have two other models, Connection and System. Each Connection has a from attribute and a to attribute, both of which I want to be System objects.

class Connection < ActiveRecord::Base
    belongs_to :map

    belongs_to :system, :class_name => "System", :foreign_key => "from"
    belongs_to :system, :class_name => "System", :foreign_key => "to"
end

class System < ActiveRecord::Base
    has_many :connections, foreign_key: "from"
    has_many :connections, foreign_key: "to"
end

This is where I'm at now. Before I was under the impression that Connection would has_one :from, :class_name "System" but that made rails look for a connection_id column in the System table.

This isn't working though.

@map.connections.each do |con|
    con.from.name #nomethod 'name' for FixNum error here
    con.to.name   #nomethod 'name' for FixNum error here
end

This however, does work.

@map.connections.each do |con|
    System.find(con.from).name
    System.find(con.to).name
end

I was just sorta working around this up until this point but I want this stuff associated properly before things get more complex.

Was it helpful?

Solution

To give any observer the reason this worked - when you set ActiveRecord associations in Rails, you're actually creating another method / attribute for your model to use

For example, when you define the association as :system, you'll be able to call @object.system in your view / controller / model. However, this also means this method is occupied - preventing you from being able to use it again (otherwise it gets overwritten)

What you discovered was that, instead of calling your associations system, calling them from and to, your associations will be handled correctly, giving you the ability to call @object.from and @object.to

OTHER TIPS

PRAISE THE SUN!!!

class Connection < ActiveRecord::Base
    belongs_to :map

    belongs_to :from, :class_name => "System", :foreign_key => "from"
    belongs_to :to, :class_name => "System", :foreign_key => "to"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top