Change a Boolean in Rails with a Button
There’s a much easier way to do this, which I show in this post.
<% if case.hidden? %> <%= button_to "Unhide", unhide_case_case_path(id: case.id) %> <% else %> <%= button_to "Hide", hide_case_case_path(id: case.id) %> <% end %>My routes file:
resources :cases do post 'hide_case', on: :member post 'unhide_case', on: :member endCases controller:
def hide_case @case = Case.find(params[:id]) @case.update(hide: true) redirect_to cases_path end def unhide_case @case = Case.find(params[:id]) @case.update(hide: false) redirect_to cases_path endHere’s how my routes look:
$ rake routes|grep hide hide_case_case POST /cases/:id/hide_case(.:format) cases#hide_case unhide_case_case POST /cases/:id/unhide_case(.:format) cases#unhide_caseThis works. However, I feel that there should have been a way for me to do this using the regular update method in the controller. The hide\_case and unhide\_case methods are basically just rewriting that method. I tried a few different ways of using the update method, but none of them worked. So until I come up with a better idea, I’ll use this. The one other thing to remember is that button\_to is an automatic POST method. (If I wanted to switch this to a link, I’d have to make some other changes because link\_to is an automatic GET method.) That’s why the routes file uses POST. The standard update uses PATCH. I’m not familiar enough with the differences between POST and PATCH to figure out if that was one of the problems I had with using the update method.