目标是复制下面sql命令使用的表。
SQL命令:
选择"产品"。*FROM"产品"INNER JOIN"products_promotion_rules"ON"产品"。"id"="products_promotion_rules"。"product_id"WHERE"products"。"deleted_at"为空且"products_promotion_rules"为空。"promotion_rule_id"=$1
My Rails关联如下:
class Product
has_many :product_promotion_rules, class_name: 'ProductPromotionRule'
has_many :promotion_rules, through: :product_promotion_rules
end
class ProductPromotionRule
belongs_to :product
belongs_to :promotion_rule
end
class PromotionRule
has_many :product_promotion_rules, class_name: 'ProductPromotionRule', join_table: 'products_promotion_rules', foreign_key: :promotion_rule_id
has_many :products, through: :product_promotion_rules
belongs_to :promotion
end
class Promotion
has_many :promotion_rules
end
我尝试过使用上面的rails关联,但我得到一个错误,即product_promotion_rules表不存在,我还得到另一个错误说Promotion::Rules::ProductValue::ProductPromotionRule is an uninitialized constant
。
看起来您正在尝试复制has_and_belongs_to_many
。这就推断出products_promotion_rules
表的存在,并且您不需要ProductPromotionRule
模型,只需要Product
和PromotionRule
:
class Product
has_and_belongs_to_many :promotion_rules
end
class PromotionRule
has_and_belongs_to_many :products
end
看起来您的模式已经就位,并且应该匹配以下内容:
Table "public.products"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Table "public.promotion_rules"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Table "public.products_promotion_rules"
Column | Type | Modifiers
-------------------+---------+-----------
product_id | integer |
promotion_rule_id | integer |