【问题标题】:Rails has_one association through mapping tableRails has_one 通过映射表关联
【发布时间】:2021-03-01 15:35:34
【问题描述】:
鉴于这 4 个 Rails 模型:
class Apple < ActiveRecord::Base
has_one: ?
end
class Banana < ActiveRecord::Base
has_one: ?
end
class FruitMapping < ActiveRecord::Base
belongs_to :fruit, polymorphic: true
has_one :cart
end
class Cart < ActiveRecord::Base
end
如何将Apple/Banana 的has_one 连接到Cart,这样我在写apple.cart 的时候就能得到相关的Cart(通过映射表)?
【问题讨论】:
标签:
ruby-on-rails
rails-activerecord
polymorphic-associations
has-one
【解决方案1】:
class Apple < ActiveRecord::Base
has_one :fruit_mapping, as: :fruit
end
class Cart < ActiveRecord::Base
has_many :fruit_mappigns
has_many :apples, through: :fruit_mappings, source: :fruit, source_type: 'Apple'
has_many :bananas, through: :fruit_mappings, source: :fruit, source_type: 'Banana'
end
使用source 和source_type 选项,您可以定义多态关系。如果使用 source 和 source_type 在您正在使用的 Rails 版本中被贬低,您可以尝试
has_many :apples, through: :fruit_mappings, class_name: 'Apple', foreign_key: :fruit_id