Rails 3.1 translate model attribute name - ruby-on-rails

I'm trying to customize (translate) an active record attribute name in rails 3.1 ("first_name"). Here's beginning of my locale file (config/locales/sv.yml):
"sv":
activerecord:
models:
employee: "Anställd"
attributes:
employee:
first_name: "Förnamn"
I'm sure this file is used by rails because changing translations further down in the file works.
Here's the form field erb code that should say "Förnamn" not "First name":
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name %>
</div>
Running Employee.human_attribute_name(:first_name) in rails console returns "First name".
Thank you very much

In Rails 3.1 you can do it this way as well:
<% form_for #post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
en:
helpers:
label:
post:
title: 'Customized title'
This approach is ORM agnostic and works fine for active model (with mongoid for instance).

I realized that I had the activerecord entry defined two times in my sv.yml translation file which ment my attributes were overridden at the top of the file. It works now.

Related

rails - how to translate what is within a ruby code in a form format?

I have a ruby code.
<%= f.label "Email *" %>
And I want to translate the English word "Email" to Japanese word because I am currently internationalizing my website written in English.
I tried the following.
<%= f.label "<%= t(:email) %> *" %>
However, it did not work. What should i do?
You should not use <% %> within another <% %>. Write it like this:
<%= f.label "#{t(:email)} *" %>
The <% tag already switches to ruby, where = also will render the outcome of the code. In order to get a translation, you might want to use <%= f.label t("email") %> and use email in your translation files.
As you need a translation inside a form, if it is bound to a model you can also translate your model as described inside the translate your models section inside the guides. Then <%= f.label :email %> will translate out of the box.
There are several ways to mark required fields, you may simply do <%= f.label "#{t("email")} *" %> or style the required field via css, like:
# app/view/.../....rb
<%= f.label :email, class: 'required' %>
# app/assets/stylesheets/.../....css
label.required:after {
content: " *";
}

Select or create from view in rails

In rails is there any simple way to implement select or create from view.
Eg:
Product has_many(or has_one) Tags.
While creating new Product I can select existing tags or create new one.
This can be done by using JavaScript and other ways are there.. But all will take more time and effort.
Please share if you know other simple way...
Edit:
Something like this.
But imagine you have 100 tags or more ! your page will look bad with 100 checkbox or more..., one elegant way to do this is by using a jQuery plugin called jQuery Tokeninput i use it in my project and it's very helpful for what do you want, you can find the plugin Here
This is a screencast on how to use it : Token fields
and this is the revised version : Token Fields (revised)
check also this blog post about the same plugin if you want too How to create a token input field where the user can also add new items
cheer
Yep.
You are after nested forms. Try, https://github.com/ryanb/nested_form
For example,
<% form_for #product do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :tags do |tag| %>
<p>
<%= tag.label :content, "Tag Name" %><br />
<%= tag.check_box :content %>
</p>
<%= tag.link_to_remove "Remove this tag" %>
<% end %>
<%= tag.link_to_add "Add new tag" %>
<p><%= f.submit "Submit" %></p>
<% end %>
Setup the controller and model as given in the documentation and try the above code in the view. This railscast will help you a lot in figuring nested forms http://railscasts.com/episodes/197-nested-model-form-part-2

Why does f.label transform 'ALL' caps string to 'All' caps

I have an object that whose values are all caps, and I would like the f.label helper to print it out as all caps - without having to do a CSS transform.
Right now, if I have the string AAPL in my object, f.label spits it out as Aapl.
The reason I don't want to use a CSS transform is because the value of the object will not ALWAYS need to be all uppercase. I just want the f.label to output it exactly as it is stored in the db - preferably without any CSS shenanigans.
How do I do that?
It sounds like something is calling humanize(). This seems to happen, when Rails translates an element name to a label title. Probably you should define the text for the label explicit to it's form element.
<%= f.label(:aapl, 'AAPL') %>
or even
<%= f.label(:aapl, #yourVar) %>
Another option for you might be the translation ability, which Rails provides. This is valid for Rails > 3.1!
In your view:
<% form_for #post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
In your en.yml:
en:
helpers:
label:
post:
title: 'Your Title'
Try this:
f.label(topic).upcase.html_safe

Rails 3 date field is blank after form submit

Rails newbie here.
I have 2 models: Target and Observation
Target works fine. I generated scaffolding for Observation, like this:
rails generate scaffold Observation date:date target:references
So app/models/observation.rb says:
class Observation < ActiveRecord::Base
belongs_to :target
end
Then I edited app/models/target.rb:
class Target < ActiveRecord::Base
has_many :observations
end
The scaffolding created app/views/observations/_form.html.erb which includes:
<div class="field">
<%= f.label :target %><br />
<%= f.text_field :target %>
</div>
And app/controllers/observation_controller.rb which includes:
def create
#observation = Observation.new(params[:observation])
I then go to create a new Observation. I enter a date and the ID of a target in the target field. When I submit, I get this error in the browser:
ActiveRecord::AssociationTypeMismatch in ObservationsController#create
Target(#2190392620) expected, got String(#2148287480)
Seems like the scaffolding would set up something that would work. But the error makes sense. It's receiving the ID of the Target instead of the Target itself. So I edited app/controllers/observation_controller.rb to say:
def create
#target = Target.find(params[:observation][:target])
#observation = #target.observations.create(:date => params[:observation][:date])
Now it creates the Observation record, with the reference to the Target. But the date field is blank.
I realize this may be a dumb newbie or RTFM question, but I'd really appreciate a pointer in the right direction. Thanks.
Here's the full contents of the form, after changing it to reflect the answer received.
<%= form_for(#observation) do |f| %>
<% if #observation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#observation.errors.count, "error") %> prohibited this observation from being saved:</h2>
<ul>
<% #observation.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
<div class="field">
<%= f.label :target %><br />
<%= f.collection_select :target_id, Target.all, :id, :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
change
<%= f.text_field :target %>
to
<%= f.text_field :target_id %>
And really better is to use something like select for this thing. Like:
<%= f.collection_select :target_id, Target.all, :id, :title %>
UPD
As far as date_select helper set not ordinary banch of variables for each element (year, month, day) you shoul do this:
date = [ params[:observation]['date(1i)'], params[:observation]['date(2i)'], params[:observation]['date(3i)'] ].join(".")
#observation = #target.observations.create(:date => date)
Actually just look into HTML source and you'll see it
(Not sure if you are still monitoring this, OP? For the benefit of everyone coming here via Google:)
There will be no params[:observation][:date] because dates are entered using several HTML input fields, and then magically merged in assignment. The keyword for this is "multi-parameter attributes", and this is the best explanation I've found:
How do ruby on rails multi parameter attributes *really* work (datetime_select)
I also wonder if this simpler snippet would work.
#observation = #target.observations.create(params[:observation])
You can use:
<%= collection_select(:observation, :target_id, Target.all, :id, :title %>
i think it will help you.

Rails i18n and yml structure for form labels

According to the ActionView documentation. Quote:
The text of label will default to the attribute name unless a translation is found in the current I18n locale (through views.labels.<modelname>.<attribute>) or you specify it explicitly.
I have a "user" model and a registration form. Here's a snippet of the relevant part:
<% form_for(#user) do |f| %>
...
<p>
<%= f.label :username %>
<%= f.text_field :username, :class => 'full_width' %>
</p>
...
<% end %>
Dots hide unimportant code.
As I understand the documentation, if I provide a translation in my locale file, in this case :dk, my dk.yml looking like so:
dk:
views:
labels:
user:
username:
"blahblah"
Rails should translate the label text and insert "blahblah" instead of "Username".
This is not happening, so I must have missed something. Any help appreciated.
In Rails 3.1 that is a little bit changed.
<% form_for #post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
en:
helpers:
label:
post:
title: 'Customized title'
I think I found another solution here.
My app was version 2.3.5. I've now changed it to 2.3.8 and <%= f.label :username %> now uses the translation in:
dk:
activerecord:
attributes:
user:
username:
I found the hint in this ticket:
https://rails.lighthouseapp.com/projects/8994/tickets/745-form-label-should-use-i18n
That's because the label method you are calling is not the one from ActionView::Helpers::FormHelper but is in fact the label_tag method from ActionView::Helpers::FormTagHelper. The form_for method is rewriting the code in the given block by adding _tag to the used form helpers. So you're not looking at the documentation for the right method!
I've not yet used that method, as sometimes the label for a field can be different from multiple forms using the same model, so I've written my own helper.

Resources