简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM