In my project I have User
objects which have multiple Order
objects.
Now on my form a user can edit his credentials and can deactivate the assigend orders:
Orderform:
- Firstname
- Lastname
- Email
- Subform Orders:
- Order1
- active
- Order n
- active
Now for any attributes on the order I can detect changes before saving the object using user.first_name_changed?
.
However, if I want to detect, if the active/inactive state changed on the orders (done with checkboxes), then I can't do user.orders_changed?
or anything along those lines.
Is there an easy way to know when the attributes of the to_many
relationship on my user object changed.
My params
that I get when I change something in the form look like this:
{
"firstname": "peter",
"lastname": "peter",
"orders_attributes": {
"0": {
"id": "1",
"is_scheduled": "1"
},
"1": {
"id": "2",
"is_scheduled": "1"
},
"2": {
"id": "3",
"is_scheduled": "1"
}
},
}
Update: I currently do the following to check if a product for a given user
changed:
def check_for_changes(user, params)
user.attributes = params
product_changed = user.product_id_changed?
# TODO: Check if any `is_scheduled` attributes changed on child-orders
# <Insert magic here>
end
Update 2:
I tried DGM's approach but curiously I can't check for is_scheduled_changed?
on my order objects:
This fails and I am not sure why the attribute is_scheduled
does not have the is_scheduled_changed?
equivalent:
user.orders.any?(&:is_scheduled_changed?)
!! #<NoMethodError: undefined method `is_scheduled_changed?' for #<Order:0x007fd5927ae620>>
Checking for the id
attribute works without an exception:
user.orders.any?(&:id_changed?) # => false
This does not raise an exception but returns always false even if I change something in the form
user.orders.any?(&:changed?) # => false