Is it possible to access attribute that is delegated to another model?

robson3999

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
mrzasa

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ActiveAdmin unknown attribute 'attribute' for Model for delegated method

Update attribute of another model

How can I access an attribute of a model which is a foreignkey to another model in the views.py file

Access to relation on another model

LoopBack access another model

Is there a way to pass model attribute into another attribute?

How to access model attribute in Javascript

How to access model attribute in jQuery

VueJS access data attribute from another attribute

Access another table over attribute

Access property inside another model

Access a model method from another model in Cake

Access listView model inside another model

How to copy a attribute of another model in rails?

Django max_length of another model attribute

Return a string representation of an attribute in another model Django

Getting attributes of a Model, which is an attribute of another one

How to access a model attribute across all templates?

Python: Possible to make attribute access strictly private?

Is it possible to access a cdef'ed attribute of super class?

Rails validate model attribute based on value of another attribute

MySQL get attribute which is not present for all possible values of another attribute

Python: access instance attribute from another file

How to access a class attribute using another variable?

Access class level attribute of another class?

Dynamicaly creating a model with a real DB as attribute of another model

How to set an instance of a model as an attribute of another model in Rails?

Is it possible to reference a Model defined in another application?

Factory Girl trouble with associations/delegated model