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!!!
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.