Drew
Drew

Reputation: 2631

How to include record id in url when form is submitted in Ruby on Rails

This is related to the question I posted here: Route a form to new controller action in Ruby on Rails

I am using a form to submit a value selected from a jquery ui autocomplete box, and using a hidden field to retain the id:

<%= form_tag "queue", method: :post, html: {id: "select_user"} do %>
    <%= hidden_field_tag('user_id', '') %>
    <%= 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, :id => u.id} }}) %>
<% end %>

Queue is a separate action on a model and controller called 'Projects' so that I can retrieve projects based on a user.

routes.rb

  match 'queue' => 'projects#queue', :as => :queue
  match 'queue/:id' => 'projects#queue', :as => 'projects_queue'

When submitting the form above, the url is now 'queue/queue', instead of 'queue/:id'. Is there any way to change this in the controller to add the user id?

Upvotes: 1

Views: 948

Answers (1)

Mike Marcacci
Mike Marcacci

Reputation: 1961

The reason you're going to 'queue/queue' is your form's action is being set as relative to the current path:

<%= form_tag "queue", method: :post, html: {id: "select_user"} do %>

should be:

<%= form_tag "/queue", method: :post, html: {id: "select_user"} do %>

to get the 'index' action on the 'queue' controller.


If you want your controller to do the redirecting, you can use the redirect_to directive like this

def index
  redirect_to "/queue/"+params[:user_id]
end

On the other hand, it might be easier to capture the click with jQuery and change the form's action:

$('#select_user').on('submit', function(e){
  var f = $(this);
  if(!f.data('action_updated')){
    e.preventDefault();
    f.attr('action','/queue/'+$('input[name=user_id]', f).val());
    f.data('action_updated', true);
    f.trigger('submit');
  }
}

Upvotes: 1

Related Questions