Chris Muench
Chris Muench

Reputation: 18318

rails generate model references type

I generated a couple models and it created the following migration files. In the 2nd migration you will see 2 references types. sub_configuration_id is a reference to the item_configurations_model. This is an optional reference (it can be NULL).

When I looked at ItemConfigurationOption model I noticed the following belongs_to :sub_configuration_id. This is not valid because belongs_to :sub_configuration_id is NOT a model. How should I reference the possible relationship for sub_configuration_id?

class ItemConfigurationOption < ActiveRecord::Base
  belongs_to :item_configuration
  belongs_to :sub_configuration_id
end

class CreateItemConfigurations < ActiveRecord::Migration
  def change
    create_table :item_configurations do |t|
      t.references :item, index: true
      t.string :name
      t.string :description
      t.integer :type

      t.timestamps
    end
  end
end


class CreateItemConfigurationOptions < ActiveRecord::Migration
  def change
    create_table :item_configuration_options do |t|
      t.references :item_configuration, index: true
      t.references :sub_configuration_id, index: true
      t.string :name
      t.string :value
      t.decimal :price

      t.timestamps
    end
  end
end

Upvotes: 0

Views: 636

Answers (1)

Mohsen Alizadeh
Mohsen Alizadeh

Reputation: 1603

Change third line to :

belongs_to  :sub_configuration, :class_name => :ItemConfiguration, :foreign_key => :sub_configuration_id

With above syntax you can declare a relation to ItemConfiguration. Then you can gen subconfiguration object with sub_configuration method.

Upvotes: 1

Related Questions