I want to create an AJAX call on an action, let's call it seen, so that a field in my database gets updated on a click. This is a follow-up question to a previous response I got yesterday, so bear with me because I am rather inexperienced.
<%= button_to "Click me!", :action => "some_action", :remote => true %>
Which will send an AJAX request back to the server, in which you need to handle in your controller
def some_actoin
// Update your database here
respond_to do |format|
format.js { render 'somepartial' }
end
end
D开发者_开发百科oes this answer essentially mean that I need to create a route associated with the def some_action? If so what format should this route take.
I don't want the user to navigate away from the page, I just simply want to update one div on the current page.
You've got a good start. When that button is clicked rails/the server will send an HTTP request to that controller/some_action. It will hit that action method where you need to save to the database. From there it will respond with javascript (hence the format.js). The javascript file it is responding with (assuming you are using jquery and not prototype) will be called some_action.js.erb . Within that file you put all of your jquery function calls etc that you want to occur once that ajax request has returned.
EDIT:
To further clarify with the routes. You need to be able to access controller/some_action as normal. This means that there needs to be a route defined:
match 'controller/some_action' => "controller#some_action"
however you don't need to do anything extra to tell rails its a remote route.
Essentially, yes you will need to add the route to the routes.rb file.
So if your controller is called posts_controller, and you want to mark a specific post as seen:
map.resources :posts, :member => {:seen => :post}
This will add a route to /posts/1/seen (where '1' is the id of the post to perform the seen action on)
精彩评论