Reputation: 905
my question is, what's the rails-way to call a method over ajax. Let's start with a quote
REST is about Path and Verb (github.com/JumpstartLab/curriculum/)
I have a method that does operations on my nested-list. Problem: How to call it over ajax when the user clicks on a link? Or at all. In Rails.
class NestedList < ActiveRecord::Base
def someListOperation # should be called when user clicks something
...
end
end
Do you
In <1> you would for instance link_to
(or other ActionView::Helpers::FormTagHelper ) the update-url with method: :patch
, while in <2> you would point it to some custom url like /nested-list/move-up/:id
Where do you generally put the logic that is not simply about updating data-fields. That's about doing something on user-action ( $('a').bind('click', function() {...}
). And what's the proper rails-way to invoke these model-methods. Following MVC such logic should go to the model, right? Because most examples (with or without ajax) only deal with updating data-fields 1-to-1 as the data comes from the form.
Thank you, Spotz.
Upvotes: 1
Views: 1688
Reputation: 1055
To achieve this you will have to add a controller action with its corresponding route. A quick example would be:
config/routes.rb:
patch "/nested-list/move_up/:id" => "nested_lists#move_up", as: :move_up_nested_list
Then on your nested lists controller:
app/controllers/nested_lists_controller.rb:
def move_up
@nested_list = NestedList.find(params[:id])
@nested_list.someListOperation
respond_to do |format|
format.html { redirect_to some_path_you_want_to_redirect }
format.js
end
end
Now you have your controller action responding to both, html(which is default) and javascript, on your view you can just add a link_to
like so:
some/view.html.erb:
link_to "Move up", move_up_nested_list_path(nested_list), method: :patch, remote: true
The only thing missing is you will have to add a js response view, in case you want to update the DOM, something like:
app/views/nested_lists/move_up.js.erb
//Your javascript code
Upvotes: 1
Reputation: 26
The way that makes the most sense to make is making a route and controller method just for that action. So'd you'd have a route and controller method with a verb corresponding to what the user did, and then that controller method would interact with the model.
Upvotes: 0