简体   繁体   中英

Creating relationships in rails 4 (one model can belong to multiple other models)

I am trying to model links and nodes in Rails 4. A link can have two nodes (a source node and a target node). A node can belong to multiple links. I wrote this in my links model.

class Links < ActiveRecord::Base
  has_one :source_node, class_name: 'Node'
  has_one :target_node, class_name: 'Node'

end

I wrote this for my node class. Is this correct?

class Nodes < ActiveRecord::Base
  belongs_to :link


end
  • SN - source node
  • TN - target node
  • L - link

Use cases for links:

SN - L - TN
SN - L
     L - TN
     L

One link has one source node.

One link has one target node.

Use cases for nodes:

     L3  
      |
L1 - SN - L2
      |
     L4

One node has many links.

So:

class Links < ActiveRecord::Base
  belongs_to :source_node, class_name: 'Node' // didn't use has_one*
  belongs_to :target_node, class_name: 'Node'
end

class Nodes < ActiveRecord::Base
  has_many :links
end

The reason to use belongs_to instead of has_one is because Link would have the foreign key to Node.

What if the relationship was defined in the opposite way? One where Node has the foreign key (belongs_to), and Link (has_one) of each type of node. With that design you would need to define a field link_N_id for N links in the Node model.

The problems are:

  • You have to manually add N fields for N links.
  • Relationships are limited to a maximum of N for each node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM