Amirol Ahmad
Amirol Ahmad

Reputation: 542

Rails4 method: :patch at index page using jquery/ajax

Would like to ask, how to make something like, lets says i have table Post and have column status (which is could be publish or unpublish).. so at the posts#index, i've button to mark as publish or unpublish.

<%= link_to 'Publish', post, method: :patch, remote: true %>
<%= link_to 'Unpublish', post, method: :patch, remote: true %>

So what I want is to update the status field through ajax using method patch.. Can someone give me an idea how to it?

Upvotes: 0

Views: 392

Answers (1)

roob
roob

Reputation: 1136

More than one way to do this. Here's a simple and straight forward way. In the view:

<%= link_to 'Publish', publish_post_path, method: :patch, remote: true %>
<%= link_to 'Unpublish', unpublish_post_path, method: :patch, remote: true %>

And add them to your config/routes.rb. This will provide the publish_post_path used in the view and direct them to the publish action in posts_controller

resources :posts do
  member do
    patch :publish
    patch :unpublish
  end
end

and finally, add the 2 actions to your controller:

  def publish
    ...
  end

  def unpublish
    ...
  end

Upvotes: 1

Related Questions