Rails 4: Can I update enums using a button?

853 Views Asked by At

I was looking at updating the database. Since I have rails 4 I found I could use enums. Now if all items statuses are set to 0 by defualt, would I be able to add a button that would change the status to 1 once its clicked.

How do I do that? Is there an example that demonstrates that because all I'm looking for is to have default status that can be changed in the view with a button.

Is that a possibility and how do I go about it? Also is a state machine gem better with this type of issue?

1

There are 1 best solutions below

0
On BEST ANSWER

You can update enums like any other attribute: Use the update action.

To send the new attribute value you could use a hidden form or attach the "form" data to a link or button.

This is how you can do it with a link/button:

link_to 'Update enum', item_path(@item), data: { method: :patch,
                                                 params: { item: { status: 1 } } }

You have to adapt the path and the names in the data-params hash to the names you are using.

Depening on your use case you might want to include remote: true to send an Ajax request.