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