Hello.

I needed to make a connection in Ruby on Rails, where one model refers to another (which is a kind of switch): in databases it looks like this:
http://goo.gl/w5sKN0

I think that this is something like a polymorphic connection, but a bit different.
Please kick me in the right direction.

UPDATE Thank you Chad for your decision. My solution to this problem is as follows:

Migration

#db/schema.rb create_table "switchs", force: true do |t| #t.references :switch, polymorphic: true - в миграции #t.references :item - в миграции t.integer "switch_id" t.string "switch_type" t.integer "item_id" end create_table "options", force: true do |t| t.string "title" ... end create_table "items", force: true do |t| t.string "name" ... end 

Accordingly, the Switch model itself will immediately have a 2a type of connection and polymorphic: and has_many: through

 #app/models/switch.rb class Switch < ActiveRecord::Base belongs_to :item belongs_to :switch, polymorphic: true ... end 

The item model refers to the model via source_type: and id in the specified source model : "switch"

 #app/models/item.rb class Item < ActiveRecord::Base has_many :switchs has_many :options, through: :switchs, source_type: "Option", source:"switch" has_many :photos, through: :switchs, source_type: "Photo", source:"switch" ... end #app/models/option.rb class Option < ActiveRecord::Base has_many :items, through: :switchs has_many :switchs, as: :switch ... end 

Well, the principle of work in all traditions rails =)

 >item = Item.create(name: "Street") >option = Option.create(title: "Manhattan") >item.options.push option 
  • @ eviper74, I think it makes sense to arrange it in the form of an answer. - Chad

2 answers 2

Perhaps Single Table Interface ...

  • I watched the STI, but did not understand the principle of operation. - eviper
  • Simply, as I understand it, in order to dynamically add elements to the database, I need to make my own sql queries, if this is an STI solution, i.e. write methods, etc. (if I understood correctly). The solution seems to be taking place too, but the solution to my problem is much simpler in the code that I wrote above =) - eviper
  • @ eviper74, a great solution, forgot about polymorph, thank you. For STI you do not need to write your own requests. The general idea there is that in one table all the fields of all classes stored there, and the type field which indicates which class of the current object. - Chad

If it is clumsy, you can make such a decision (then you can figure out how to make it quite beautifully, the main thing is to share how :-))

 class PolyMorph < ActiveRecord::Base def linked_object #тут главное чтобы был контроль на то что попадает в eval eval(self.model).find(self.id_in_model) end def linked_object=value value.save! self.id_in_model = value.id self.model = value.class.to_s end end 

As the author of the question figured out, the standard asset asset paradigm for this is polymorphism .