Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating dynamic url based on form inputs

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.

like image 927
the Areba Avatar asked Sep 14 '25 07:09

the Areba


2 Answers

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]
like image 108
the Areba Avatar answered Sep 16 '25 21:09

the Areba


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

update

in your routes file use these routes:

match '/currencies/', to: 'converter#show',   via: [:post]
  post '/currencies/:url_end' => 'converter#show'

i hope that helps.

like image 40
ben Avatar answered Sep 16 '25 22:09

ben