首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >范围依赖属性

范围依赖属性
EN

Stack Overflow用户
提问于 2013-12-13 19:34:54
回答 2查看 37关注 0票数 0

有模型定价:

代码语言:javascript
复制
pricingable_id:integer
pricingable_type:string
**store_id**:integer
cost_price:decimal
margin:integer
discount:integer
active:boolean

还有其他的模型产品:

代码语言:javascript
复制
name
description
...

has_many :pricings, as: :pricingable

那么,我如何委托属性cost_price、保证金、折扣、从产品到定价依赖于store_id (单一)?

尝试了一些类似于has_one :pricing,-> { where store_id: Store.current_id }之类的东西,但是没有道理。

UPD:我需要从产品模型中指定定价属性:

代码语言:javascript
复制
Store.current_id = 1

p = Product.new
p.cost_price = 100
p.margin = 10
p.discount = 5
p.active = true
p.save

pricing = Product.**pricing** (not pricings, one pricing depending to current store)
pricing.cost_price
=> 100
EN

回答 2

Stack Overflow用户

发布于 2013-12-13 19:46:34

我建议改变你们的联系。

价格(与定价不同,在我看来是不直观的)应该与Product相关联。

在这个布局中,一切都非常简单,我认为这就是你想要实现的。

前:

代码语言:javascript
复制
Price.where(product_id: Product.first, store_id: 1).cost_price

编辑例子。

比方说,在Costco、Walmart和Aldi三家商店里,都有一种有id 1的燕麦片产品。(ids 1.3)

如果你想在送礼店(比如说沃尔玛)改变这种产品的价格,你可以这样做

代码语言:javascript
复制
Price.where(store_id: 2, product_id: 1).update {}

更多的例子。

给定产品的所有价格:

代码语言:javascript
复制
Product.first.joins(:prices)

商店的所有价格(及相关价格):

代码语言:javascript
复制
Store.first.joins(products: :prices)
票数 1
EN

Stack Overflow用户

发布于 2013-12-13 19:45:50

听起来你想要一个多态关联..。请查看本rails指南中的主题:

basics.html#polymorphic-associations

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20574552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档