Search code examples
ruby-on-railsruby-on-rails-4database-migrationhas-manybelongs-to

Can't figure out has_many/belongs_to RAILS 4


My models are:

class CarBrand < ActiveRecord::Base
        has_many :car_models
    end

class CarModel < ActiveRecord::Base
    belongs_to :car_brand
end

and my migrations are

    class CreateCarBrands < ActiveRecord::Migration
  def up
    create_table :car_brands do |t|
      t.string "brand", :limit => 20    
      t.timestamps null: false
    end
  end

  def down
    drop_table :car_brands
  end
end

    class CreateCarModels < ActiveRecord::Migration
   def up
    create_table :car_models do |t|
      t.references :car_brand
      t.string "model", :limit => 20      
      t.timestamps null: false
    end
    add_index :car_models, :car_brand_id
  end
  def down 
    drop_table :car_models
  end
end

and i want to get car models according to specific car brand, in database i have both records, but when i type in console it gives error

somecar = CarBrand.where(:brand => 'Toyota')
somecar.car_models

so it doesn't returns me models of toyota, but i have them in database!!!


Solution

  • Try like that:-

    somecar = CarBrand.where(:brand => 'Toyota')
    somecar.first.car_models
    

    As CarBrand.where(:brand => 'Toyota') returns an array.

    OR

    Try like that:-

    somecar = CarBrand.find_by brand: 'Toyota'
    somecar.car_models
    

    CarBrand.find_by brand: 'Toyota' will fetch first matching record.