简体   繁体   中英

Rails: call model-methods (with ajax)

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

  1. Put a switch-block into, say, the #update action to decide if and what method(s) to call? Then one would pass the method-name along with the required parameters ?
  2. Make a route just for the method ?
  3. Some special third option only available through ajax-magic

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM