Reputation: 19
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!!!
Upvotes: 0
Views: 39
Reputation: 777
somecar = CarBrand.where(:brand => 'Toyota')
returns an active record relation #<ActiveRecord::Relation [#<.....
the main point is that it is a collection. You have to iterate over each item in the collection.
some_cars = CarBrand.where(:brand => 'Toyota')
some_cars.each do |car| puts car.car_model end
or on the first item some_cars.first.car_model
Notice I changed some_car to some_cars, the name of the variable does matter but it is easier to see that it is a collection. Notice I called .car_model
(and NOT car_models
) on each item, that really is important.
Upvotes: 1
Reputation: 2451
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.
Upvotes: 0