Вопрос

I've got a weird issue with one of my forms. The form only changes one variable of the object, called admin_comment. It ends up in the show method of the controller, in the terminal:

Processing by EnrolmentsController#show as

Here is the form_for

<%= form_for enrolment, :url => enrolments_admin_comment_path(enrolment), method: :get, remote: true do |f| %>

And here is the rake routes

enrolments_admin_comment GET    /enrolments/admin_comment(.:format)              enrolments#admin_comment

And the routes.rb part

  get "enrolments/admin_comment"

  resources :courses do
      resources :enrolments
  end

When I delete the method: :get part from the form_for, it ends up at the update method. Everything else with the enrolments controller/model works fine. Does somebody know what's going on here? Thanks!

Update After nearly getting insane I've got it working like this, but only with :get as method.

routes.rb

  get "/enrolments/:id/admin_comment" => "enrolments#admin_comment", as: "enrolments_admin_comment"

form_for

<%= form_for enrolment, :url => enrolments_admin_comment_path(enrolment), method: :get, remote: true do |f| %>

If I change the method to :post, I get the following error:

ActionController::RoutingError (No route matches [POST] "/enrolments/28/admin_comment"):

Two questions came up: 1. What do I have to change to make it work with :post? 2. As far as I understand, if I just would just state the controller and the verb (:get / :post / ...), rails would know which method it has to use as the verbs are mapped to the methods. But when I state the whole path (controller and method), shouldn't rails know everything it needs without the verb? The form params are being sent anyway.

Update2 Ok, I've changed

get "/enrolments/:id/admin_comment" => "enrolments#admin_comment", as: "enrolments_admin_comment"

to

post "/enrolments/:id/admin_comment" => "enrolments#admin_comment", as: "enrolments_admin_comment" 

Now everything works fine.

Это было полезно?

Решение

You'll be best looking at Rails' Resource Routing


HTTP Verbs

Each resources :controller you create in your routes.rb file creates a series of routes, which connect with relative HTTP Verbs:

HTTP Verbs

The HTTP verbs part of the routing system is the most important, as it governs which controller action is loaded. You can use the same path helper with different HTTP Verbs to route to completely different controller actions

If you want to create a new path, you'd need to set the HTTP verb to method: :post, like this:

<%= form_for enrolment, :url => enrolments_admin_comment_path(enrolment), method: :post, remote: true do |f| %>

Routes

Perhaps you'd be better with this routing structure:

  resources :courses do
      resources :enrolments do
          get :admin_comment, shallow: :true
      end
  end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top