ruby-on-rails - Is it possible to access attribute that is delegated to another model?
问题描述
When creating app I had model Order with attribute delivery_option
. After some time, I had to create "higher level" order
to group orders and created MainOrder.
Now, Order delegates :delivery_option
to MainOrder, but about 70% of MainOrders has delivery_option == nil
because where created during migration, just to cover Orders from past. I couldn't fill up main_order.delivery_option = order.delivery_option
because there can be many orders in one main_order, each with different :delivery_option
.
Is it possible to somehow access order.delivery_option
without hitting order.main_order.delivery_option
?
code looks like this:
class MainOrder
has_many :orders
end
class Order
belongs_to :main_order
delegates :delivery_option, to: main_order, allow_nil: true
end
解决方案
You can use the attributes
method returning a hash with attribute values:
order = Order.first
# fetches delivery_option from the main_order
order.delivery_option
# returns value stored in orders table belonging to the order
order.attributes["delivery_option"]
# you can also use
order.attribute(:delivery_option)
推荐阅读
- javascript - 我可以在单击图标时显示确认信息吗?
- r - 如何在 R 中生成这样的点图?
- javascript - 如何暂停承诺,直到我在 js、firebase 中获得用户操作?
- php - 如何在 PHP 中更改 Google 表格的缩放级别
- r - R降价主题不编织
- javascript - 如何淡化元素背景图像的边缘以与主背景图像融合?
- swift - 使用 GCD,DispatchGroup 如何在组离开之前(或之后)从后台队列在主队列上运行项目,而不会出现死锁?
- android - Jenkins - 移动 .android 文件夹位置
- flutter - 无法从 Firebase 中检索数据,并且它不显示来自 Firebase 的数据
- javascript - React Native:onChangeText 没有更新钩子状态