I'm on Ruby 2.0 and Rails 4, and trying to render an array of lines to f.text_area form helper using:
<%= f.text_area :sources_text, value: ['1', '2'].join('\n') %>
I expect to get:
1
2
as the <textarea> value but I get:
1\n2
What I'm doing wrong?
In the helper the value is being rendered as a string.
So to have
1
2
you have to have the value be "1\n2"
so if you have an array t then:
<%t=['1','2']%>
<%= f.text_area :sources_text, value: t.join("\n") %>
and you will have in the text area
1
2
Use: "\n". The '\n' version used single quotes '', which escape almost nothing.
Dev tip: Always prefer '' unless you actually need ""'s special powers (which you do need, here).
Related
the following
#ids.class
is being properly returned as Array
But when it is being used as values
<%= button_tag 'Top', value: #ids, type: :submit, name: :top %>
the params submitted are:
"top"=>"17515 30784 31614 32342 32362 31815 31813 32386 33004 32483 31750 32478 16331 11728"
which is a string.
> params[:top].class
String
Transforming via Array(params[:top]) only results in a single element
["17515 30784 31614 32342 32362 31815 31813 32386 33004 32483 31750 32478 16331 11728"]
Transforming via substitution of space with a comma, to then generate a proper array
params[:top].sub(" ", ",")
only handles the first space
"17515,30784 31614 32342 32362 31815 31813 32386 33004 32483 31750 32478 16331 11728"
Modifying the tag to value: #ids.to_s returns the same situation.
How can this be properly processed by the subsequent action as an array?
How can this be properly processed by the subsequent action as an array?
Unless you want to do some wonky parameter processing like params[:top].split(' ') you need to use multiple parameters in a form or query string to pass an array.
To pass array parameters in Rack (the CGI that Rails sits on top of) you need to pass multiple formdata pairs where the key ends with [].
foo[]=1&foo[]=2&foo[]=3
# resulting params hash
=> { "foo" => ["1", "2", "3"] }
This is actually processed the same way regardless if its passed in the query string or request body.
For query strings #to_query handles this automatically:
irb(main):004:0> CGI.unescape( { foo: [1,2,3]}.to_query )
=> "foo[]=1&foo[]=2&foo[]=3"
For forms you can just create hidden inputs:
<% values.each do |v| %>
<%= hidden_field_tag 'top[]', v %>
<% end %>
Max's answer is correct but will use n hidden form fields to generate the foo[]=1&foo[]=2&foo[]=3 response.
If you still want to use it with the button_tag input field you can do something like the following
# In your form file
<%= button_tag 'Top', value: #ids, type: :submit, name: :top %>
And then use it like that in your controller
# Use #split on the string params
params[:top].split
Example
"10 20 30".split => ["10", "20", "30"]
You can always pass a delimiter to split by on the #split method
#split documentation
Usually to add a word (for my multilanguage website) I use this system: <%= t('.title') %>
Now in config/locales/en.yml, I added something like this:
en:
home:
title: Title
title_0: Finally Sunday! Watch this title
title_1: Hey! It's monday! This is the Title
And I want to use Time.now.wday and to create something like <%= t('.title_#{Time.now.wday}') %>
But it doesn't work. How to write it correctly?
That's because you need double quotes for string interpolation in Ruby. Just replace
<%= t('.title_#{Time.now.wday}') %>
for
<%= t(".title_#{Time.now.wday}") %>
although it maybe should be
<%= t("home.title_#{Time.now.wday}") %>
because title, title_0 and title_1 are nested under home
Interpolation does not work with single quotes
That means that:
puts "Works in double quoted strings: #{1 + 2}."
puts 'Not not work in single quoted strings: #{1 + 2}.'
will print out:
"Works in double quoted strings: 3."
"Does not work in single quoted strings: #{1 + 2}."
source: http://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html
I am using a text_field to enter 24 hour time on a form. The regular expression works for everything but and empty string. Why?
<div class="field">
<%= f.label :start_tod %><br>
<%= f.text_field :start_tod,
value: (tod_to_str(#availability.start_tod) || '00:00'),
pattern: '([01][0-9]|2[0-3])[:|\.][0-5][0-9]|24[:|\.]00',
title: '00:00 to 24:00' %>
</div>
To check the 24 hour text format, as HH:mm you can use the following regex:
([01]?[0-9]|2[0-3]):[0-5][0-9]
in the first part you have one group, that will handle hours separetely, with rules for hours started with 0 and 1. The last part if for the numbers.
You should also add some validation on your model, based on the same regexp, and decide if you want to save an empty string or a nil value when the user don't fill anything.
I'd like to debug a variable #num in my Rails controller, so I'm evaluating
<%= #num %>
in my Rails view. However, I cannot distinguish between #num being '', ' ', and ' ' (and other different types of whitespace) when it's printed in the HTML. Is there any way to print it out clearly?
If you want to be really sure:
<%= #num.inspect %>
When #num = ' ' this should render:
" "
#inspect is great when you want to a representation of some object as a string.
If this is a complex object or large array or deep hash, I often prefer #to_yaml for inspection which lays it out in a somewhat readable format.
# controller
#foo = {:a => [:bar, :baz], :b => 123, :c => 'omg'}
# view
<pre><%= #foo.to_yaml %></pre>
# visible output
---
:b: 123
:c: omg
:a:
- :bar
- :baz
<%=debug #num %>
Will format it in haml.
<%= #num.inspect %>
Will format it as "p" does.
See Debugging Rails Applications (rails guides)
What I'm trying to do:
I'm trying to find out if there is a quick way to get country_select to store integers representing the countries instead of storing the country names/strings themselves. I'm using the country select gem.
Possible solution:
One way I'm thinking this can be done is if I install the gem as a plugin and edit the countries array to have arrays within the main array with integers and a string e.g. COUNTRIES = [["United Kingdom", 1],["United States", 2]]
This way in my form there will be values representing the strings. Then I can have a country_id column in my profiles table where users selected countries id will be stored. I will have a separate table "countries" that will have the countries stored in it and I'll use the country_id of the profiles table to reference the correct country in the countries table.
Doing it this way would mean I would still get the good features of the gem/plugin such as having priority countries at the top of the select list. Something I don't know how to do on my own.
It would take long but it could work. If I chose this solution where would I put the plugin? vendors folder in my apps directory right?
But if there is a quicker way to do this I'd like to do it that way.
A bigger picture:
Ok I have a search form where a user can browse the sites users filtering out results by:
text typed location
gender
sexuality
marital status
country
I'm using thinking sphinx and when filtering attributes it seems that the attributes need to be represented integers because everything works but the country.
I'm using the country select gem and it seems to only store strings and not an integer representing the string.
I would like to have it store integers instead.
Here are some contants I use in my search forms:
module ApplicationHelper
GENDER = [["Select", nil],["Male", 1],["Female", 2]]
ETHNICITY = [["Select", nil],['Black', 1 ],['White / Caucasian', 2 ],['European', 3 ],['Asian', 4 ],
['Indian', 5 ],['Middle Eastern', 6 ],['Native American', 7 ],['Hispanic', 8 ],
['Mixed Race', 9 ],['Other Ethnicity', 10 ]]
MARITAL_STATUS = [[' Select', nil],['Single', 1 ],['Dating', 2 ],['In relationship', 3 ],['Married', 4 ],
['Living Together', 5 ],['Divorced', 6 ],['Separated', 7 ],['Widowed', 8 ]]
SEXUAL_PREFERENCE = [[' Select', nil],['Straight', 1 ],['Gay', 2 ],['Bi-sexual', 3 ]]
end
The search/browse form:
<%= form_tag browsers_path, :method => 'get' do %>
<p>
Location: <%= text_field_tag :location, params[:location] %>
<br />
Country: <%= country_select :country, [ "United Kingdom", "France", "Germany" ] %>
<br />
Gender: <%= select_tag :gender, options_for_select(ApplicationHelper::GENDER, params[:gender]) %>
<br />
Ethnicity: <%= select_tag :ethnicity, options_for_select(ApplicationHelper::ETHNICITY, params[:ethnicity]) %>
<br />
Marital status: <%= select_tag :marital_status, options_for_select(ApplicationHelper::MARITAL_STATUS, params[:marital_status]) %>
<br />
Sexual preference: <%= select_tag :sexual_preference, options_for_select(ApplicationHelper::SEXUAL_PREFERENCE, params[:sexual_preference]) %>
<br />
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
as you can see each array has a string and an integer. If you check out the array from the country_select gem there are just strings.
I'd appreciate an explanation of the best possible way to do what I'm trying to do and a clear example if possible.
I hope this post made sense.
Kind regards
I ended up recreating the country list from wikipedia with name of country and iso code as value. Much more straight forward and I got to store countries as their iso code and as integers making it possible to use the attribute with thinking sphinx.
Create the constant like you have for the other filters. Then use a virtual attribute to translate and set the values so that you can store the int version and not the string.
EDIT:
Maybe I do not understand what we are talking about exactly but if you are trying to store the value in a model somewhere you can do something like this:
def country_int(country_s)
country = COUNTRY[country_s]
end
def country_int
COUNTRY.key(country)
end