Passing user input in link_to params - ruby-on-rails

I am trying to pass an user input into link_to params. I know generally you use forms but here I am not linking these params to a particular model so I just want to access the user input and then pass it to params when user clicks on the link.
Something like this:
Ask for user input - <div><%= date_field :date%></div>
Then pass it in params -
<td><%= link_to "Send", controller_func_path(date: 'date_field value') %></td>

You do not need to link the form to a model to send input data. You can use the form to send the input data as follows:
foo.html.erb
<%= form_with url: boo_action_path do |form| %>
<%= form.text_field :foo %>
<%= form.submit 'Send' %>
<% end %>
foo_controller.rb
class FooController < ApplicationController
def boo
foo_input_value = params[:foo]
end
end

Demir is right, sending data with normal forms is more practical. However, if changing links on the fly is a strict requirement, you can do so with javascript:
<script type='text/javascript'>
function changeLink() {
date = document.getElementById('date_changeable').value;
targetHref = document.getElementById('tochange')
baseLink = targetHref.dataset.baseLink
document.getElementById('tochange').href = baseLink + date;
}
</script>
<%= date_field 'date', 'changeable', onchange: 'changeLink()' %>
<td><%= link_to "Send", 'http://example.com', data: { base_link: 'http://example.com' + '/' }, id: 'tochange' %></td>

Related

Passing Rails 5 Form Value to Controller as Paramerter

I am having trouble passing a non-model form field from view to controller. The value I am trying to pass is amount
Thank you.
views/donations/index.html.erb
<%= form_tag donations_path, style: (current_user.card_last4? ? "display:none" : nil) do %>
<div id="error_explanation">
<% if flash[:error].present? %>
<p><%= flash[:error] %></p>
<% end %>
</div>
<article>
<%= label_tag(:amount, 'Donation Amount:') %>
<%= text_field_tag(:amount) %>
</article>
<%= link_to 'Donate', new_donation_path(amount: :amount), class: 'btn btn-primary', id: 'donateButton' %>
<% end %>
controllers/donations_controller.erb
def create
customer = current_user.stripe_customer
amount = params[:amount]
token = params[:stripeToken]
begin
Charge.charge(amount, token)
end
...
models/charge.rb
def self.charge(amount, token)
charge = Stripe::Charge.create(
amount: amount,
source: token,
currency: 'usd',
description: 'Test Charge'
)
end
...
Use a view tag like
<%= text_field_tag 'donation[amount]' %>
And permit the parameter in your controller
def donation_params
params.require(:donation).permit(:amount)
You can access the value with donation_params[:amount].
You shouldn't use link_to to trigger the form submission. Use submit_tag instead. Besides that, make sure your strong params whitelist whatever you're submitting.
I guess you are not using strong params. Why not just add |f| at the end like this
<%= form_tag donations_path, style: (current_user.card_last4? ? "display:none" : nil) do |f| %>
and then use <%= f.text_field :amount %>
Then at the params you should do something like params["donation"]["amount"] to get the value
EDIT: at the end change link_to for f.submit

how to link form_tag to button rails 4

I have a selection box on my page, and when I click the submit button I want to take the selection choice to the server as either a post or get variable (I don't think it matters). How do I link this form:
<%= form_tag(store_rates_path, method: 'get') %>
<%= label_tag(:year, "From (year)") %>
<%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>
to this button:
<%= button_tag(link_to("Get Rates", store_rates_path))%>
You only need to provide the path to the form_for method, to link it to the rates action of your stores controller:
<%= form_tag(store_rates_path, method: "get") do %>
<%= label_tag(:year, "From (year)") %>
<%= select_tag(:year, options_for_select((1980..2014).to_a)) %>
<%= button_tag "Get Rates" %>
<% end %>
In your rates action you can then retrieve the :year parameter passed as follows:
def rates
#year = params[:year]
end
You also need to define the route in your routes.rb file as follows, if you haven't yet:
get 'stores/rate', to: 'stores#rate', as: 'store_rates'
IMPORTANT
Just note that if the rates belong to a specific store, meaning the url is something like stores/1/rate then the above get must be stores/:id/rate, which also means you need to pass the store.id to the store_rates_path in your form: store_rates_path(#store)
You can use rails submit_tag helper
<%= form_tag(store_rates_path, method: 'get') %>
<%= label_tag(:year, "From (year)") %>
<%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>
<%= submit_tag "Get Rates" %>
<% end %>
OR
If you want to use a link or button to submit your form parameters then you can use some js magic to achieve it:
<%= form_tag store_rates_path, id: "store-form", method: 'get' %>
<%= label_tag(:year, "From (year)") %>
<%= select_tag(:year, options_for_select(get_select_options(1980, 2014))) %>
<%= link_to "Get Rates", "#", id: "store-form-btn" %>
<% end %>
$(document).on("click","#store-form-btn",function(e){
e.preventDefault();
$("#store-form").submit();
});

How to Get value of text_field rails

I have a text field as:
<%= text_field :search, :class=>'input-xxlarge search-query',:id=>'keyword' %>
Then on click of a link I want to pass the value in this text field to a
controller method.
I do not want to use a form and form submit.
I have the link as:
<a href ="/home/search" >GO</a>
and to this 'search' method I want to pass the text field value....
also to go directly to the page "/home/search" designed to this action "search"
How do I do this???
Thank you...
Read here link_to send parameters along with the url and grab them on target page
<%= link_to "Go", '/home/search?param1=value' %>
So if you won't use form, you should use jQuery for put value of field into attribute link (href) with parameter.
Example on jsffidle
<%= text_field :search, :class=>'input-xxlarge search-query',:id=>'keyword' %>
<%= link_to "Go", '', :id => "searchlink" %>
$(':input').bind('keypress keydown keyup change',function(){
var word = $(':input[id="keyword"]').val();
$('a[id="searchlink"]').attr("href","/home/search?param1=" + word.toString());
});
and in controller:
if params[:param1] == ""
render :search # or redirect whatever do you want
else
param = params[:param1]
....
end
In your routes file
resources :home do
member do
get 'search'
end
end
In your html
<div id='parentDiv'>
<%= text_field :search, nil, :class=>'input-xxlarge search-query',:id=>'keyword' %>
<%= link_to("GO", '#', :class => 'search-link')
</div>
In the javascript file
$(document).ready(function(){
$('div#parentDiv').on('click', '.search-link', function(){
var search_val = $('#keyword').val().trim();
if(search_val != ''){
window.location.href='/home/'+search_val+'/search';
} else{
alert('You need to enter some data');
}
});
});
And in your search action
def search
search_value = params[:id]
# your code goes here.
end
Try something like this...(not tested). This will give you the logic.
<%= link_to "Go", "#", onclick: "window.location = \"www.sitename.com/home/search?q=\"+$(\"#keyword\").val()" %>

Nested child modification

I'm working on this dynamic form to create multiple nested child form, just like in ryan bates railscast, but i want to specify the amount of nested child before input:
Here's the for controller in ryan's railscast :
def new
#invoice = Invoice.new
5.times { #invoice.items.build }
end
So i'm wondering if i can change nested child to dynamicly multiply based from an input form:
I've tried this code below, but it didn't work:
def new
count = params[:item_counts] ---> the value from a text_field_tag
count.times { #invoice.items.build }
end
Here's the view:
<div id="invoice">
<%= form_tag invoices_path, :method => "get" do %>
<%= label_tag :items, "Item amounts :" %><%= text_field_tag :item_counts %><br /><br />
<%= link_to 'Create New Invoice', new_invoice_path(invoice) %>
<% end %>
</div>
How to pass the value from :item_counts in the text_field_tag to the controller?
What do you mean by passing the value to the controller ? If you submit the form, all your params ( including params[:item_counts] ) will be passed to invoices#create, i.e. create action of invoices controller.
What exactly is the params passed to the posted new method ?

In Rails, how to create a dropdown menu that fills in parameters to a path to navigate to?

Trying to create a select menu with items from a collection, so that upon selection of an item, and hitting submit, the user is taken to the "Show" action for that item...What I have is something like this:
<% form_tag("subjects/#{#subject.id}/state/:id", :method=>:get) do %>
<%= select_tag('state', options_from_collection_for_select(State.states, 'id', 'name'))%>
<%= submit_tag "go!" %>
<% end %>
What'd I like is for what's selected in the menu to fill in the :id parameter...(this is rails 2.3)
You can send the form to an action that redirect where you want:
<% form_tag("some_controller/redirection", :method=>:get) do %>
<%= select_tag('id', options_from_collection_for_select(State.states, 'id', 'name'))%>
<%= hidden_field_tag :subject_id, #subject.id %>
<%= submit_tag "go!" %>
<% end %>
in SomeController
def redirection
redirect to "subjects/#{#{params[:subject_id]}}/state/#{params[:id]}"
end
The structure of the URL that you are requesting can't be made using only an HTML form. It will require some Javascript:
$('#my_form').submit(function(){
window.location = '/subjects/' + $('#subject_id').val() + '/state/' + $('#state_id').val();
});

Resources