问题
Hello everyone.
I have a form in my rails 3 app, and one of the fields is a "collection select" like this
<div class="field">
<%= f.label :provider_id, "Provider" %>
<%= collection_select( :purchase_document, :provider_id, Provider.all, :id, :name) %>
</div>
The idea, is to be able to add a "link_to" using the selected value from the "collection select" i.e.:
<div class="field">
<%= f.label :provider_id, "Provider" %>
<%= collection_select( :purchase_document, :provider_id, Provider.all, :id, :name) %> <%= link_to "Show", provider_path(***selected option from collection select***)%>
But, I don't know how to get the selected value. Is there a rails way to do that?
Hope you can help me, thanks
回答1:
Don't know if this is what you want to do, but if you want to dynamically change the link as the user selects different items from the drop-down menu, you need implement this with client side scripting, such as Javascript (or Coffeescript). Ruby on Rails can only perform server side scripting, any dynamic behaviors related to the browser has to be done with client side scripting.
回答2:
It is perfectly possible to do in rails without javascript. We keep all parameters in params (that is in the url), and we submit a form with method "get" (not post as usual), so we can have all this params in the url.
Following example should work to write a name in a text field and get a page where the name is passed as parameter to the url. (for instance http://myapp.com:3000?user_name=andres&phone_number=123456
)
View file:
= form_tag(reloadindex_aplication_path, method: :get) do
Name:
= text_field_tag 'user_name', params[:user_name]
Phone:
= text_field_tag 'phone_number', params[:phone_number]
= submit_tag "Search..."
Controller file:
def reloadindex
redirect_to aplication_path({:user_name => params[:user_name], :phone_number => params[:phone_number]})
end
来源:https://stackoverflow.com/questions/7827138/rails-3-make-a-link-to-using-selected-value-from-collection-select