0

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
Besi
  • 22,579
  • 24
  • 131
  • 223

1 Answers1

0

If the form is loaded with the usual nested resource methods, does this work?

user.orders.any?(&:changed?)

Basically check all of the nested orders for any changes.

DGM
  • 26,629
  • 7
  • 58
  • 79
  • I always get a `false` using your approach, even if I change the checkbox that affects `is_scheduled`. Do I have to add the `order_attributes` to all the orders, before I can check this? (See my updated answer that shows how I currently check for the product relationship). – Besi Oct 28 '13 at 07:36