Frage

In my app I'm toggling whether a student belongs to a training time or not when clicking on a time link.

# controller
def time
  @student = Student.find(params[:student_id])
  @time = TrainingTime.find(params[:training_time_id])
  @student.toggle_time(@time)
  respond_to do |format|
    format.html { redirect_to @student }
    format.js
  end
end

# routes
resources :students do
  match "time/:training_time_id", to: "students#time", as: :toggle_time
end

# view
<%= link_to t.time_format, student_toggle_time_path(@student, t), remote: true %>

Currently it's working using match, but what is the proper way of setting this up and why?

Thanks for your input.

War es hilfreich?

Lösung

It's all about semantics. GET to fetch a resource, POST to create a resource, PUT (or PATCH, these is debate on the matter) to update a resource, DELETE to delete one.

To be honnest, there is debate about POST and PUT too. But since web servers usually only handles GET and POST (the behavior of other verbs being emulated via parameters), I tend not to bother too much, and stick with what I wrote above.

You don't seem to be creating any resource, so semantically speaking, PUT is what you're looking for.

As for match, in rails 3.X, is a catch all => all verbs are matched in the route. You can restrain using match 'something', via: [:get, :post]. With Rails 4, by default it will do nothing, you have to be explicit about the verbs handled.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top