首页 > 解决方案 > 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

标签: ruby-on-railsrubydelegates

解决方案


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)


推荐阅读