[英]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!!! 因此它不会返回丰田的型号,但我将其保存在数据库中!!!
somecar = CarBrand.where(:brand => 'Toyota')
returns an active record relation #<ActiveRecord::Relation [#<.....
the main point is that it is a collection. somecar = CarBrand.where(:brand => 'Toyota')
返回活动记录关系#<ActiveRecord::Relation [#<.....
要点是它是一个集合。 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
或在第一项上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. 注意,我将some_car更改为some_cars,变量的名称确实很重要,但是更容易看出它是一个集合。 Notice I called .car_model
(and NOT car_models
) on each item, that really is important. 请注意,我在每个项目上都调用了.car_model
(而不是car_models
),这确实很重要。
Try like that:- 这样尝试:-
somecar = CarBrand.where(:brand => 'Toyota')
somecar.first.car_models
As CarBrand.where(:brand => 'Toyota')
returns an array. 如CarBrand.where(:brand => 'Toyota')
返回一个数组。
OR 要么
Try like that:- 这样尝试:-
somecar = CarBrand.find_by brand: 'Toyota'
somecar.car_models
CarBrand.find_by brand: 'Toyota'
will fetch first matching record. CarBrand.find_by brand: 'Toyota'
将获取第一个匹配记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.