[英]Rails has_one and belongs_to join
在我的應用程序中,我有以下模型:汽車:
class Car < ActiveRecord::Base
has_one :brand, through: :car_configuration
has_one :model, through: :car_configuration
has_one :body_style, through: :car_configuration
has_one :car_class, through: :car_configuration
belongs_to :car_configuration
end
汽車配置:
class CarConfiguration < ActiveRecord::Base
belongs_to :model, class_name: 'CarModel'
belongs_to :body_style, class_name: 'CarBodyStyle'
belongs_to :car_class
has_one :brand, through: :model
has_many :cars, dependent: :destroy
has_many :colors, dependent: :destroy
def brand_id
brand.try(:id)
end
end
和CarBrand:
class CarBrand < ActiveRecord::Base
default_scope { order(name: :asc) }
validates :name, presence: true
has_many :models, class_name: 'CarModel', foreign_key: 'brand_id'
end
現在,我想獲取所有CarConfiguration品牌ID例如為1的Cars。我嘗試了類似的操作,但這不起作用:
joins(:car_configuration).where(car_configurations: {brand_id: 1})
在此先感謝您的幫助。
社團協會
我不認為你可以有一個belongs_to :through
關聯( 通過協會belongs_to的 ),而且,您的模型看起來很臃腫我
我看一下使用has_many :through
關聯 :
#app/models/brand.rb
Class Brand < ActiveRecord::Base
has_many :cars
end
#app/models/car.rb
Class Car < ActiveRecord::Base
#fields id | brand_id | name | other | car | attributes | created_at | updated_at
belongs_to :brand
has_many :configurations
has_many :models, through: :configurations
has_many :colors, through: :configurations
has_many :body_styles, through: :configurations
end
#app/models/configuration.rb
Class Configuration < ActiveRecord::Base
#id | car_id | body_style_id | model_id | detailed | configurations | created_at | updated_at
belongs_to :car
belongs_to :body_style
belongs_to :model
end
#app/models/body_style.rb
Class BodyStyle < ActiveRecord::Base
#fields id | body | style | options | created_at | updated_at
has_many :configurations
has_many :cars, through: :configurations
end
etc
這將允許您執行以下操作:
@car = Car.find 1
@car.colours.each do |colour|
= colour
end
面向對象
其他要考慮的是Ruby(&Rails) object-orientated
性質。
面向對象的編程不僅僅是一個時髦的流行詞,它還是應用程序的核心基礎結構元素,因此,您需要考慮圍繞對象構造模型等:
這意味着,當您創建模型以調用Car
對象之類的模型時,您需要欣賞創建的associations
應直接補充該特定對象
您的協會目前不執行此操作-它們非常隨意且結構錯誤。 我建議您檢查要填充/創建的對象,然后圍繞它們創建應用程序
從您的角度來看,來自CarConfiguration的brand_id不是模型的屬性,因此,您無法在嘗試時查詢...
解決方案是首先選擇良好的汽車配置並獲得所有相應的汽車:
CarConfiguraton.joins(:brand).where(brand: {id: 1}).cars
def self.with_proper_brand(car_brands_ids)
ids = Array(car_brands_ids).reject(&:blank?)
car_ids = Car.joins(:car_configuration).all.
map{|x| x.id if ids.include?(x.brand.id.to_s)}.reject(&:blank?).uniq
return where(nil) if ids.empty?
where(id: car_ids)
end
那就是答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.