Route a form to new controller action in Ruby on Rails

前端 未结 3 1656
遥遥无期
遥遥无期 2021-01-25 17:23

I am relatively new to Ruby on Rails, and am trying to set up a form with a new action on an existing controller.

My existing model and controller is called \'projects\'

3条回答
  •  一个人的身影
    2021-01-25 17:56

    The answers from Josh and Billy can accomplish this well, to throw another hat into the mix I would suggest making this a route based off of the projects. Assuming your routes are restful and contains projects as resources projects:

    resources :projects do 
       post "queue", :on => :collection
    end
    

    What this does is add the route projects/queue to your routes since it is based off of the collection instead of a member. See: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions for more info.

    It is worth noting why this happens. It is because the the route you are originally posting to is only queue when what you want is queue/:id since the id is specified via a url parameter you should use a get request. But since it looks like you are posting the id via a post request this is a little confusing. Choosing just to use a post request you do not need the url parameter like Billy suggested and I also agree since this will allow you to keep it a but more succinct.

    Hope this helps!

    Edit For username usage

    Changing your form to:

    <%= form_tag("queue", :id => "select_user", :method => "post") do %>
        <%= hidden_field_tag(:username) %>
        <%= text_field_tag('user', nil, :placeholder => 'Enter a user...', class: "users",
                           data: {autocomplete_source: User.order(:lastname, :firstname).map { |u| {:label => u.firstname + " " + u.lastname, :username => u.username} }}) %>
    <% end %>
    

    Assuming the JS is working as it should, you just need to populate the hidden field with the :username value instead of :id. Then on the controller side of things:

      def queue
        @projects = Project.find_all_by_username(params[:username])
      end
    

    Hope this makes sense!

提交回复
热议问题