是否可以访问委托给另一个模型的属性?

时间:2019-09-20 08:20:08

标签: ruby-on-rails ruby delegates

在创建应用程序时,我的模型订单具有属性delivery_option。一段时间后,我不得不创建“​​更高级别” order来对订单进行分组并创建MainOrder。 现在,订单委托:delivery_option到MainOrder,但是大约70%的MainOrders具有delivery_option == nil,因为在迁移过程中创建的位置只是为了覆盖过去的订单。我无法填写main_order.delivery_option = order.delivery_option,因为一个main_order中可以有很多订单,每个订单都有不同的:delivery_option

是否可以通过某种方式访问​​order.delivery_option而无需点击order.main_order.delivery_option

代码如下:

class MainOrder
  has_many :orders
end

class Order
  belongs_to :main_order
  delegates :delivery_option, to: main_order, allow_nil: true
end

1 个答案:

答案 0 :(得分:3)

您可以使用attributes方法返回具有属性值的哈希:

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)