For example, I have a model Post with a boolean value called active, how can I easily change this value for true or false from the list of posts in the index.html.erb with a link_to or button_to helper like remote: true?
1 Answer
You can get a controller method, say toggle_active to set the active status of your post like follow:
def toggle_active
@post = Post.find(params[:id])
status = [email protected]
@post.active = status
respond_to do |format|
if @post.save
render json: "success"
else
render json: "failure"
end
end
end
then, get a route to this action in your routes.rb:
get 'post/:id/toggle-active' => 'post#toggle_active'
this should give you a toggle_active_post_path or something similar.
that is the path that you will now target from inside your view, with the button_to, or link_to, as the case may be.
<%= link_to "Activate/Deactivate", toggle_active_post_path(id: post.id), remote: true %>
And yes, you set remote: true to enable the ajax call.
One more thing: you need to define a corresponding toggle_active.js.erb file, to handle the response from the ajax.
Hope this helps...
1 Comment
rii
Another way of setting status would be using the built in Rails method "toggle" apidock.com/rails/ActiveRecord/Base/toggle