Encoding UTF-8 in Rails form parameter name - ruby-on-rails

I'm having a problem with my params.
I'm receiving the following parameters:
{"utf8"=>"✓", "authenticity_token"=>"...=", "Portugu\xC3\xAAs"=>{"title"=>"313" } }
In my controller I need to use the key => "Portugu\xC3\xAAs", but first I need it to be in the right form (that is -> Português) and I don't know how can I do that.
EDIT:
Workflow
1. The user saves a language
2. I use that language in a form to save information, like this:
Português[title]
3 . Because the user can have multiple locales in that form (all the locales saved in step 1)
locales.each do |locale|
...
:value => params[locale.key][:title]
The problem is that locale.key ('Português') doesn't match with "Portugu\xC3\xAAs" so it crashes with nil
Can you help me with this?
Thank you

I've tried this, and the result is good:
<% p = {}
p["Português"] = {}
p["Português"][:title] = "Title in Portugês" %>
<p><%= p["Portugu\xC3\xAAs"][:title] %>
And I get
<p>Title in Portugês</p>
I don't see the problem.

The solution that worked for me was iterating the received params and with the help of URI.escape compare the string, if matches enc_locale is set and used in the value.
Thanks to everyone that helped!
enc_locale = ""
params.each do |param|
if URI.escape(param[0]) == URI.escape(locale.key)
enc_locale = param[0]
end
end
...
:value => params[enc_locale][:title]

Related

Ruby on Rails - parameter gives nil result back

parameter
"day" => "2013-11-21"
controller
date = params[:day] # gives me a nil value back
#event = Event.new(date: date, id: date.id)
view
...
<% f.hidden_field :id, :value => :day %>
...
Here are the parameters:
{"utf8"=>"✓",
"authenticity_token"=>"lxKzvpGx8nmutI8X8sdZGNaKZ8w1kJEdF/B8ixtqpqA=",
"event"=>{"title"=>"",
"description"=>"",
"day"=>"2013-11-21",
"start(1i)"=>"2013",
"start(2i)"=>"11",
"start(3i)"=>"22",
"start(4i)"=>"08",
"start(5i)"=>"00",
"end(1i)"=>"2013",
"end(2i)"=>"11",
"end(3i)"=>"22",
"end(4i)"=>"08",
"end(5i)"=>"00"},
"commit"=>"Create Event"}
why gives it to me a nil value back?
let me know if you need something more
You should use params[:event][:day] instead of params[:day]
I see at least three problems.
Your param is accessible through params[:event][:day], as you should see in the parameters list you posted.
The hidden field you posted doesn't set params[:event][:day] parameter. Actually, it does nothing as it isn't even being rendered (because of <% usage, instead of <%=.
You try to misuse this parameter, calling id on it (in #event = Event.new(date: date, id: date.id) line). Even if you refer to that parameter properly, it will raise an error.

Rails I18n, check if translation exists?

Working on a rails 3 app where I want to check if a translation exists before outputting it, and if it doesn't exist fall back to some static text. I could do something like:
if I18n.t("some_translation.key").to_s.index("translation missing")
But I feel like there should be a better way than that. What if rails in the future changes the "translation missing" to "translation not found". Or what if for some weird reason the text contains "translation missing". Any ideas?
Based on what you've described, this should work:
I18n.t("some_translation.key", :default => "fallback text")
See the documentation for details.
You can also use
I18n.exists?(key, locale)
I18n.exists?('do_i_exist', :en)
:default is not always a solution. Use this for more advanced cases:
helpers/application.rb:
def i18n_set? key
I18n.t key, :raise => true rescue false
end
any ERB template:
<% if i18n_set? "home.#{name}.quote" %>
<div class="quote">
<blockquote><%= t "home.#{name}.quote" %></blockquote>
<cite><%= t "home.#{name}.cite" %></cite>
</div>
<% end %>
What about this ?
I18n.t('some_translation.key', :default => '').empty?
I just think it feels better, more like there is no translation
Caveat: doesn't work if you intentionally have an empty string as translation value.
use :default param:
I18n.t("some_translation.key", :default => 'some text')
sometimes you want to do more things on translations fails
v = "doesnt_exist"
begin
puts I18n.t "langs.#{v}", raise: true
rescue
...
puts "Nooo #{v} has no Translation!"
end
This is a trick but I think it may be useful sometimes...
Assuming you have this in your i18n file:
en:
key:
special_value: "Special value"
default_value: "Default value"
You may do this:
if I18n.t('key').keys.include?(:special_value)
I18n.t('key.special_value')
else
I18n.t('key.default_value')
end
# => "Special value"
if I18n.t('key').keys.include?(:unknown_value)
I18n.t('key.special_value')
else
I18n.t('key.default_value')
end
# => "Default value"
NB: This only works if you're testing anything but a root key since you're looking at the parent.
In fact, what's interesting is what you can get when requesting a parent key...
I18n.t('key')
# => {:special_value=>"Special value", :default_value=>"Default value"}
Rails 4
I was iterating over some urls of jury members. The max amount of urls were 2, and default_lang was "de". Here is the yaml that I used
de:
jury:
urls:
url0: http://www.example.com
name0: example.com
url1:
name1:
en:
jury:
urls:
url0:
name0:
url1:
name1:
Here is how I checked if there was a url given and if it did not exist for another language, it would fallback to the I18n default_lang "de". I used answer of #albandiguer which worked great.
I Hope this helps someone:
<% 2.times do |j| %>
<% if I18n.exists?("jury.urls.url#{j}", "de") &&
I18n.exists?("jury.urls.name#{j}", "de") %>
<%= "<br/>".html_safe if j == 1%>
<a href="<%= t("jury.urls.url#{j}") %>" target="_blank">
<%= t("jury.urls.name#{j}") %>
</a>
<% end %>
<% end %>
Some versions ago there is a easier way i18next documentation > API > t:
You can specify either one key as a String or multiple keys as an Array of String. The first one that resolves will be returned.
Example:
i18next.t ( ['unknown.key', 'my.key' ] ); // It will return value for 'my.key'
Also you can use Contexts. t if not found a key into a context returns the default value.

Rails form formatting

I've just had Submitting multiple forms in Rails answered which led to another problem. In my form I have the following (there's quite a bit more):
= hidden_field_tag :event_id, :value => #event.id
.control-group
= label_tag :title
.controls
= select(:registration, "registrations[][title]", Registration::TITLE)
and the last line returns:
"registrations"=>[{"title"=>{"registration"=>"Mr"},
as opposed to the expected:
"title"=>"Mr"
I've tried:
= select(:registration, "registrations[][title]", Registration::TITLE)
which returns:
undefined method `registrations[][title]' for #
and also tried:
= select("registrations[][title]", Registration::TITLE)
which returns:
wrong number of arguments (2 for 3)
Look at the parameters below, event(_id) is only there once then the :title oddness starts, any idea what the problem may be?
{"utf8"=>"✓",
"authenticity_token"=>"BQXm5fngW27z/3Wxy9qEzu6D8/g9YQIfBL+mFKVplgE=",
"event_id"=>"7",
"registrations"=>[{"title"=>{"registration"=>"Mr"},
"first_name"=>"Name1",
"last_name"=>"Surname1",
"company_name"=>"Company1",
"designation"=>"Designation1",
"landline"=>"Landline1",
"cell"=>"Cell1",
"email"=>"address1#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None"},
{"first_name"=>"Name2",
"last_name"=>"Surname2",
"company_name"=>"Company2",
"designation"=>"Designation2",
"landline"=>"Landline2",
"cell"=>"Cell2",
"email"=>"address2#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None",
"title"=>{"registration"=>"Mr"}},
{"first_name"=>"Name3",
"last_name"=>"Surname3",
"company_name"=>"Company3",
"designation"=>"Designation3",
"landline"=>"Landline3",
"cell"=>"Cell3",
"email"=>"address3#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None"}],
"commit"=>"Submit registrations"}
Please not that :dietary and :member are formated in the same way as :title. Thanks in advance for your assistance!
EDIT
So submitting to the hash via a text_field_tag is a simple is:
= text_field_tag "registrations[][first_name]"
But the problem comes in with my hidden_field_tag and select_tag.
It's adding bad values, for example:
"title"=>{"registrations"=>"Mr"}
and basically it seems I need to find a better way to add those values into the hash. I'll continue trying to find a solution and will post it here unless someone beats me to it.
Unless i'm reading it wrong, your first two select calls are the same. Have you tried = select(:registrations, "title", Registration::TITLE)? If you look at the documentation of the method in api.rubyonrails.org, it will state that the first value is the object, second is the property. That would be registrations => { :title => "Value" }, in the parameters. If you just want :title => "Value", then you need the select_tag method.

How to display Rails select field values rather than stored integers in other views

I'm using a select field in a Rails app that is NOT tied to a related model, but stores integer values for a static series of options , i.e.,
<%= select (:this_model, :this_field, [['Option1',1],['Option2',2],['Option3',3],['Option4',4]] ) %>
In a show/ index view, if I want to display the option text (i.e. Option1, Option2, etc) rather than the integer value stored in the database, how do I achieve this?
Thanks for helping a noob learn the ropes!
EDIT
Based on Thorsten's suggestion below, I implemented the following. But it is returning nil, and I can't figure out why.
Invoice model:
##payment_status_data = { 1 => "Pending Invoice" , 2 => "Invoiced" , 3 => "Deposit Received", 4 => "Paid in Full"}
def text_for_payment_status
##payment_status_data[payment_status]
end
Invoice show view:
Payment Status: <%= #invoice.text_for_payment_status %>
In the console:
irb > i=Invoice.find(4)
=> [#<Invoice id: 4, payment_status: 1 >]
irb > i.text_for_payment_status
=> nil
I've tried defining the hash with and without quotes around the keys. What am I missing?
something like this would work:
<%= form_for #my_model_object do |form| %>
<%= form.label :column_name "Some Description" %>
<%= form.select :field_that_stores_id, options_for_select({"text1" => "key1", "text 2" => "key2"}) %>
<% end %>
Update
If you later want to display the text you can get it from a simple hash like this:
{"key1" => "text 1", "key2" => "text2"}[#my_object.field_that_stores_id]
But you better store this hash somewhere in a central place like the model.
class MyModel < ActiveRecord
##my_select_something_data = {"key1" => "text 1", "key2" => "text2"}
def text_for_something_selectable
##my_select_something_data[field_that_stores_id]
end
end
Then you can use it in your views like
#my_object.text_for_something_selectable
There are many possible variations of this. But this should work and you would have all information in a central place.
Update
Ok, I used something similar for our website. We need to store return_headers for rma. Those need to store a return reason as a code. Those codes are defined in an external MS SQL Server Database (with which the website exchanges lots of data, like orders, products, and much more). In the external db table are much more return reasons stored than I actually need, so I just took out a few of them. Still must make sure, the codes are correct.
So here goes he model:
class ReturnHeader < AciveRecord::Base
##return_reason_keys = {"010" => "Wrong Produc",
"DAM" => "Damaged",
"AMT" => "Wrong Amount"}
def self.return_reason_select
##return_reason_keys.invert
end
def return_reason
##return_reason_keys[nav_return_reason_code]
end
end
Model contains more code of course, but that's the part that matters. Relevant here is, that keys in the hash are strings, not symbols.
In the views i use it like this:
In the form for edit:
<%= form_for #return_header do |form| %>
<%= form.label :nav_return_reason_code "Return Reason" %>
<%= form.select :nav_return_reason_code, options_for_select(ReturnHeader.return_reason_select, #return_header.nav_return_reason_code) %>
<% end %>
(Maybe no the most elegant way to do it, but works. Don't know, why options_for_select expects a hash to be "text" => "key", but that's the reason, why above class level method returns the hash inverted.)
In my index action the return reason is listed in one of the columns. There I can get the value simply by
#return_headers.each do |rh|
rh.return_reason
end
If you have trouble to get it run, check that keys a correct type and value. Maybe add some debug info with logger.info in the methods to see what actual data is used there.

Passing hash as values in hidden_field_tag

I am trying to pass some filters in my params through a form like so:
hidden_field_tag "filters", params[:filters]
For some reason the params get changed in the next page. For example, if params[:filters] used to be...
"filters"=>{"name_like_any"=>["apple"]} [1]
...it gets changed to...
"filters"=>"{\"name_like_any\"=>[\"apple\"]}" [2]
note the extra quotations and backslashes in [2] when compared to [1].
Any ideas? I'm attempting to use this with searchlogic for some filtering, but I need it to persist when I change change objects in forms. I would prefer not to have to store it in session.
My solution was just to re-create each of param with key-value pair:
<% params[:filters].each do |key,value| %>
<%= hidden_field_tag "filters[#{key}]",value %>
<% end %>
You actually want/need to 'serialize' a hash using hidden fields.
Add this to your ApplicationHelper :
def flatten_hash(hash = params, ancestor_names = [])
flat_hash = {}
hash.each do |k, v|
names = Array.new(ancestor_names)
names << k
if v.is_a?(Hash)
flat_hash.merge!(flatten_hash(v, names))
else
key = flat_hash_key(names)
key += "[]" if v.is_a?(Array)
flat_hash[key] = v
end
end
flat_hash
end
def flat_hash_key(names)
names = Array.new(names)
name = names.shift.to_s.dup
names.each do |n|
name << "[#{n}]"
end
name
end
def hash_as_hidden_fields(hash = params)
hidden_fields = []
flatten_hash(hash).each do |name, value|
value = [value] if !value.is_a?(Array)
value.each do |v|
hidden_fields << hidden_field_tag(name, v.to_s, :id => nil)
end
end
hidden_fields.join("\n")
end
Then, in view:
<%= hash_as_hidden_fields(:filter => params[:filter]) %>
This should do the trick, even if you have a multilevel hash/array in your filters.
Solution taken http://marklunds.com/articles/one/314
I just wrote a gem to do this called HashToHiddenFields.
The core of the gem is this code:
def hash_to_hidden_fields(hash)
query_string = Rack::Utils.build_nested_query(hash)
pairs = query_string.split(Rack::Utils::DEFAULT_SEP)
tags = pairs.map do |pair|
key, value = pair.split('=', 2).map { |str| Rack::Utils.unescape(str) }
hidden_field_tag(key, value)
end
tags.join("\n").html_safe
end
Here's how I managed to pass a parameter value through my view - that is, from View A through View B and on to the controller:
In View A (index):
<%= link_to 'LinkName', {:action => "run_script", :id => object.id} %>
In View B (run_script):
<%= form_tag :action => 'index', :id => #object %>
<%= hidden_field_tag(:param_name, params[:id]) %>
In the controller:
Just reference params[:param_name] to make use of the value.
The key transition that wasn't documented anywhere I could find is where {... :id => object.id} from View A is passed on to View B as <%... :id => #object %>, which View B then passes on to the controller as (:param_name, params[:id]) through the hidden_field_tag construct.
I didn't see this documented anywhere but after perusing several posts across several sites including this post (whose syntax provided the key inspiration), the solution finally gelled. I've seen the caveats on hidden fields pertaining to security but have found no other way to do this given my current design, such as it is.
it's because when you convert in HTML with your hidden_field_tag, the backquote is add. After when you received it like a string not a Hash.
The Hash type can't exist in HTML. You have only string. So if you want pass your hash (not recommend by me), you need eval it when you received it. But can be a big security issue on your application.
As a caveat to Vlad's answer, I had to use raw:
<%= raw hash_as_hidden_fields(:filter => params[:filter]) %>
to get it to work in Rails 3.1.1. Essentially, the text being output was being escaped, eg., "<" becoming "&lt".
Assuming the hash is strings, symbols, numbers, and arrays, you can call eval to convert the params string of the hash from the hidden_fields form back into a hash in the controller. Then the backslash escape characters for the quotes added are no longer an issue:
hash = eval(params["hash_string"].to_s)
Credit to the following article for helping identify this simple solution for my case:
How do I convert a String object into a Hash object?
Keep in mind the contents of the params should be cleaned with .require and .permit.

Resources