I need to generate a url based on two drop-down inputs, from currency and two currency such that when a user clicks submit button, the url generated should look like http://localhost:3000/currencies/usd-eur
when form currency is usd and to_currency is eur for example.
Here's my views(index.html.erb)
<%= semantic_form_for :calculator, :url => {:controller => "conversions", :action => "calculate" } do |f| %>
<p><%= f.label :amount %>
<%= f.text_field :amount %></p>
<p><%= f.label :from_currency %>
<%= select :calculator, :from_currency, Choices['from_currency'] %></p>
</p><%= f.label :to_currency %>
<%= select :calculator, :to_currency, Choices['to_currency'] %></p>
<p><%= f.submit "Calculate" %></p>
<%= end %>
routes.rb
match 'currencies', to: 'conversions#index', via: :get
match 'currencies/convert', to: 'conversions#calculate', as: :calculate, via: :post
controller(conversions_controller.rb)
def index
end
def calculate
@amount = params[:calculator][:amount]
@from_cur = params[:calculator][:from_currency]
@to_cur = params[:calculator][:to_currency]
@result = ConversionsHelper.calculate(@from_cur, @to_cur, @amount)
end
I don't have any models for that matter since I get my data from google API hence I could be going outside the boundaries of RESFFUL conventions. A detailed answer would be appreciated. Thanks.
This javascript code ended up solving my problem.
$(document).ready(function(){
$('#Cal').attr('action', '/currencies');
$("#Cal").submit(function(e){
var from = $('#calculator_from_currency').val().toLowerCase();
var to = $('#calculator_to_currency').val().toLowerCase();
var url_end = from + "-" + to;
var url = $('#Cal').attr('action') + '/' + url_end;
$('#Cal').attr('action', url);
});
});
Then I added this line in my routes.
post '/currencies/:url' => 'conversions#calculate', via: [:post]
try using jquery, to pick your values from the form. then set the url by
$('form#currency_form').attr('action', url);
in side your form
in your routes file use these routes:
match '/currencies/', to: 'converter#show', via: [:post]
post '/currencies/:url_end' => 'converter#show'
i hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With