Questions on method return values and arguments after do - ruby-on-rails

sorry for this noob question I am just not able to understand ruby/rails grammer,
In rails 2.x, I read the following code,
def localized_input_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
args << options.merge(:builder=>LocalizedFormBuilder)
concat('<div class="inputbox">')
form_for(record_or_name_or_array, *args, &proc)
concat('</div>')
end
What does the above function return? Shouldn't it be the return value of the last line statement concat('</div>')?
In the views, I have,
<% localized_input_form_for(#customer) do |f| %>
What is the f in the above code, is it the same f as form_for(xx) do |f|?
The following code works without problem,
<%= f.text_field :name, :required => true, :size => 30,:class =>'ime_on' %>
In rails 4, I made the following modification,
def localized_input_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
args << options.merge(:builder=>LocalizedFormBuilder)
concat('<div class="inputbox">'.html_safe)
concat(form_for(record_or_name_or_array, *args, &proc))
concat('</div>'.html_safe)
end
Without adding concat out of form_for, and without adding html_safe, the original code just doesnt work.
Now, everything still works, the
<% localized_input_form_for(#customer) do |f| %>
works without problem, the form is shown exactly as before. So what is the return value of this function now? and what is f above?
The only difference is, the original options in
<%= f.text_field :name, :required => true, :size => 30,:class =>'ime_on' %>
which are, required: true, size: 30, and class:'ime_on' don't show in the final html!
It generates the following,
<input type="text" value="abc" name="customer[name]" id="customer_name">
without size, class etc options. The html generated by rails 2.x do have these options showing up.
I am just confused about the difference. And I also don't understand why the original rails 2.x and rails 4 both worked (the |f| reflects the form generated by form_for, so f.text_field will get the right value from database).

Yes, your method will return the last line. In your case this is concat("</div>") which evaluates to just "</div>".
The problem is, that concat is not acting as you expect, because it's not occurring within a text buffer and so there's nothing to "concat" to.
To fix this, wrap your helper in a capture block like so:
def some_html
capture do
# ...
concat('<div class="inputbox">')
# ...
concat('</div>>
end
end
More on the capture method: http://apidock.com/rails/ActionView/Helpers/CaptureHelper/capture

Related

I18n translated values do not show up if changed from helper method rails

Hello not sure how to explain this but i will give it my best shot.
I hv a model like this
class Answer < ActiveRecord::Base
EMPLOYMENT_TYPE = [
['Employed', I18n.t('self_evaluation.self_evaluation_form.employment_status.employed')],
['Self-Employed', I18n.t('self_evaluation.self_evaluation_form.employment_status.self_employed')],
['Unemployed / Retired', I18n.t('self_evaluation.self_evaluation_form.employment_status.unemployed')]
]
end
I also have a helper method that calls this
module AnswerHelper
def get_employment_type_list
return Answer::EMPLOYMENT_TYPE
end
end
And a partial view that should display the values like this
_step_1.html.erb
<% employment_list = get_employment_type_list %>
<%= employment_list %>
<div class="flex_center flex_column button-wrap">
<%= collection_radio_buttons("application[answer_attributes]", :employment_type, employment_list, :first, :last, item_wrapper_tag: false, checked: #selected_employment_type) do |b|
b.label(class: 'employment_type_radio') { b.radio_button(:onchange => "return_employment_type(value)", class:'radio-label') + b.label(class:'button-label'){b.text}}
end %>
</div>
_step_2.html.erb
<% employer_list = get_employer_list(chosen_employment_type(#decoded_self_evaluation)) %>
<% employer_type = #decoded_self_evaluation.try(:loan_application).try(:kyc_answer).try(:employer_type) %>
<div class="flex_center flex_column button-wrap">
<%= collection_radio_buttons("loan_application[kyc_answer_attributes]", :employer_type, employer_list, :first, :last, item_wrapper_tag: false, checked: employer_type) do |b|
b.label(class: 'employer_type_radio') { b.radio_button(:onchange => "is_business_registered(value)", class:'radio-label') + b.label(class:'button-label'){b.text}}
end %>
</div>
identity.js
$.ajax({
url:'/self_evaluations/' + self_evaluation_id + '/employment_type',
method:"POST",
data:JSON.stringify({employment_type: employment_type, key: $('#token_key').val()}),
contentType:"application/json; charset=utf-8",
dataType:"script",
async: false,
success: function(data) {
$valid = true;
}
})
employment_list.js.erb
$('#id_employer').empty();
$('#id_employer').append("<%=j render 'self_evaluations/self_evaluation_partials/step_2' %>");
Now the problem is that i have already added all that's needed for I18n translations to happen in Rails and for texts that are translated on the html view it works correctly when i switch from the different languages but for texts that are been gotten via a helper method like this. Based on initial help, on initial load, all page work fine but if i change the language and then run an ajax call that loads the employment_list.js.erb my locale seems to still be the primary language the the values do not change accordingly
Not sure why this is happening anyone faced something like this before?
Because you declared the translations as a constant in your model, so the translations were loaded just one time when Answer model was loaded in the first time.
In production environment, the model will be loaded after starting server. In development environment, the model will be loaded when the file content is changed, ...
In order to solve your issue, you can add the translations in your helper instead:
module AnswerHelper
def get_employment_type_list
[
['Employed', I18n.t('self_evaluation.self_evaluation_form.employment_status.employed')],
['Self-Employed', I18n.t('self_evaluation.self_evaluation_form.employment_status.self_employed')],
['Unemployed / Retired', I18n.t('self_evaluation.self_evaluation_form.employment_status.unemployed')]
]
end
end
I usually use this approach, please have a look!
class Answer < ActiveRecord::Base
EMPLOYMENT_TYPE = [:employed, :self_employed, :unemployed_or_retired]
end
module AnswerHelper
def get_employment_type_list
i18n_scope = 'self_evaluation.self_evaluation_form.employment_status'
Answer::EMPLOYMENT_TYPE.map do |type|
[type, t(type, scope: i18n_scope)]
end
end
end

Formatting credit card number in a number_field_tag [duplicate]

I would like to make editing form fields as user-friendly as possible. For example, for numeric values, I would like the field to be displayed with commas (like number_with_precision).
This is easy enough on the display side, but what about editing? Is there a good way to do this?
I am using the Rails FormBuilder. Upon investigation, I found that it uses InstanceTag, which gets the values for fields by using <attribute>_value_before_type_cast which means overriding <attribute> won't get called.
The best I have come up with so far is something like this:
<%= f.text_field :my_attribute, :value => number_with_precision(f.object.my_attribute) %>
Or my_attribute could return the formatted value, like this:
def my_attribute
ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end
But you still have to use :value
<%= f.text_field :my_attribute, :value => f.object.my_attribute %>
This seems like a lot of work.
I prefer your first answer, with the formatting being done in the view. However, if you want to perform the formatting in the model, you can use wrapper methods for the getter and setter, and avoid having to use the :value option entirely.
You'd end up with something like this.
def my_attribute_string
foo_formatter(myattribute)
end
def my_attribute_string=(s)
# Parse "s" or do whatever you need to with it, then set your real attribute.
end
<%= f.text_field :my_attribute_string %>
Railscasts covered this with a Time object in a text_field in episode #32. The really clever part of this is how they handle validation errors. It's worth watching the episode for that alone.
This is an old question, but in case anyone comes across this you could use the number_to_X helpers. They have all of the attributes you could ever want for displaying your edit value:
<%= f.text_field :my_number, :value => number_to_human(f.object.my_number, :separator => '', :unit => '', :delimiter => '', :precision => 0) %>
There are more attributes available too: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html
If you want a format to be created or maintained during editing, you will need to add Javascript to implement "masks." Here is a demo.
It was the first hit in these results.
You can use the number_format plugin. By specifying a number_format for an existing numeric attribute inside your model, the attribute will now appear as formatted to Rails in all forms and views. It will also be parsed back from that format (when assigned via forms) prior to insertion into the database. (The plugin also creates purely numeric unformatted_<attribute-name> accessors which can continue to be used for arithmetic, or for direct numerical assignment or retrieval by you for seamless integration.)
class MyModel < ActiveRecord::Base
# this model has the balance attribute, which we
# want to display using formatting in views,
# although it is stored as a numeric in the database
number_format :balance,
:precision => 2,
:delimiter => ',',
:strip_trailing_zeros => false
def increment_balance
unformatted_balance += 10
end
You can also combine the above with a Javascript solution, which can force the user to maintain the decimal point and thousands separators in place while editing, although this is really not necessary.
I have done something similar. We format times and lengths using a custom form builder. It makes use of the existing text_field, but wraps it so the value can be customized:
class SuperFormBuilder < ActionView::Helpers::FormBuilder
include ApplicationHelper
include FormHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::FormTagHelper
def length_field(label,*args)
scale = 'medium'
args.each do |v|
if v.has_key?(:scale)
scale = v[:scale]
v.delete(:scale)
end
end
value = length_conversion(#object.send(label.to_sym),scale)
options = (args.length > 0) ? args.pop : {}
return has_error(label, text_field_tag(field_name(label),value,*args) + ' ' + length_unit(scale))
end
private
def field_name(label)
return #object_name + "[#{label}]"
end
def has_error(label, output)
return "<div class='fieldWithErrors'>#{output}</div>" if #object.errors[label]
return output
end
And it is used like this:
<%= form_for( #section, {:action => 'save', :id => #section.id}, :builder => SuperFormBuilder) do |sf| %>
<%= sf.length_field :feed_size_min_w, :size => 3, :scale => 'small' %>
<% end %>
The end result is a value in the appropriate unit based off their choice on system (Metric, Imperial) and scale IE small = inches or millimeters.
I basically copied the text_field method from the existing form builder, which uses the text_field_tag itself.
There are two gotchas: 1) Knowing the name of the object field and how to access the object to get the value which you want to format. 2) Getting the name right so when the form is submitted it is part of the correct params hash.
The form builder is given a class variable #object. You can get the value of the field using the .send method. In my case I send the label :feed_size_min_w to the #object and get its length back. I then convert it to my desired format, and give it to the text_field_tag.
The name of the field is key to having it end up in the params hash, in my instance the params[:sections] one. I made a little helper function called field_name that takes care of this.
Finally the has_error wraps the field in an error div if there are errors on that label.
I needed "nicer" format on some specified text fields, resolved it by adding this to my initializers. Seems to work nicely on Rails ~= 5.2 and it should be easy to customize.
class ActionView::Helpers::Tags::TextField
private
def value_before_type_cast # override method in ActionView::Helpers::Tags::Base
v = super
# format as you like, when you like
if #options.delete(:nice_decimal)
v = v.to_s.gsub('.', ',') if v.is_a?(BigDecimal)
end
v
end
end
Usage in form f
<%= f.text_field :foo, nice_decimal: true %>

How to extract info from input field in ruby

I'm a frontend + PHP dev, trying to fix [] in a project built in Rails.
[] = Fetch color, show a slightly darker color.
This row:
<%= f.text_field attribute %>
creates an input field with a value that can be translated into a color. I'm at loss as to where to look for how it adds that value. I'm trying to use the value that this input field generates.
this is code from the file select_a_color_input.html.erb inside the app/views/shared folder. Any ideas on where to continue my treasure hunt? :)
update: I found this!
def app_text_field(attribute, args = {})
render_field 'text_field', field_locals(attribute, args)
end
Does that help? ^__^
update:
The form builder
class AppFormBuilder < ActionView::Helpers::FormBuilder
def form_fields(partial = nil , options = {})
partial ||= 'form'
fields = ''
unless options.delete(:without_error_messages)
fields << #template.render('shared/error_messages', :target => Array(#object).last)
end
fields << #template.render(partial, options.merge(:f => self))
end
def app_text_field(attribute, args = {})
render_field 'text_field', field_locals(attribute, args)
end
def app_file_field(attribute, args = {})
render_field 'file_field', field_locals(attribute, args)
end
private
def render_field(name, locals)
#template.render field_path(name), locals
end
def field_locals(attribute, args = {})
help_options = args[:help_options] || {}
field_options = args[:field_options] || {}
html_options = args[:html_options] || {}
{ :f => self, :attribute => attribute, :help_options => help_options, :field_options => field_options, :html_options => html_options, :object => object }
end
def field_path(value)
"shared/app_form/#{value}"
end
end
update:
When I tried to add
<%= content_tag(:p, attribute) %>
It does not give me the values, but instead the id/name of the item, not the colour.
<%= f.text_field attribute %>
This by itself is not very useful to help us gather context. What's the surrounding markup look like? attribute is a ruby variable in this instance. If it were f.text_field :attribute, then :attribute is now a symbol instead of a variable and this would indicate that it maps to the attribute method on X model. This all depends on what your form_for looks like though. I'll give an example:
<%= form_for #user do |f| %>
<%= f.text_field :attribute %>
In this case, we have a form for the User model, and our text_field maps to #user.attribute. The field itself looks something like this:
<input type='text' name='user[attribute]'>
And in the controller's #update or #create action (depending on if this is a new record or an existing record you're editing) the value would be accessible in this fashion:
params[:user][:attribute]
However, it's impossible to say what exactly the params will look like in your particular case. What action is being run? What's the name of the file that this is being loaded from? "app/views/users/new" would indicate the #new action handles this page, and the #create action will handle the form submission.
Things we need to know to fully solve your problem:
Name and relevant code of the controller that's handling this action.
Full view path that this is being rendered from
The rest of the markup starting at form_for and ending at this field attribute
What value does attribute hold? It's a variable, so it must be holding a symbol value or something that will indicate which field is being mapped to this input.

Rails 4.0 Strong Parameters nested attributes with a key that points to a hash

I was playing around with Rails 4.x beta and trying to get nested attributes working with carrierwave. Not sure if what I'm doing is the right direction. After searching around, and then eventually looking at the rails source and strong parameters I found the below notes.
# Note that if you use +permit+ in a key that points to a hash,
# it won't allow all the hash. You also need to specify which
# attributes inside the hash should be whitelisted.
https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb
So its saying you have to specify every single every single attribute within the has, I tried the following:
Param's example:
{"utf8"=>"✓",
"authenticity_token"=>"Tm54+v9DYdBtWJ7qPERWzdEBkWnDQfuAQrfT9UE8VD=",
"screenshot"=>{
"title"=>"afs",
"assets_attributes"=>{
"0"=>{
"filename"=>#<ActionDispatch::Http::UploadedFile:0x00000004edbe40
#tempfile=#<File:/tmp/RackMultipart20130123-18328-navggd>,
#original_filename="EK000005.JPG",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"screenshot[assets_attributes][0][filename]\"; filename=\"EK000005.JPG\"\r\nContent-Type: image/jpeg\r\n">
}
}
},
"commit"=>"Create Screenshot"}
Controller
def screenshot_params
params.require(:screenshot).permit(:title,
:assets_attributes => [:filename => [:#tempfile,:#original_filename,:#content_type,:#headers]
The above isn't "working" (its not triggering carrierwave) however I am no longer getting errors (Unpermitted parameters: filename) when using the standard nested examples I found ex:
def screenshot_params
params.require(:screenshot).permit(:title, assets_attributes: :filename)
If anyone could help it would be great. I was not able to find a example with nested with a key that points to a hash.
My other answer was mostly wrong - new answer.
in your params hash, :filename is not associated with another hash, it is associated with an ActiveDispatch::Http::UploadedFile object. Your last code line:
def screenshot_params
params.require(:screenshot).permit(:title, assets_attributes: :filename)
is actually correct, however, the filename attribute is not being allowed since it is not one of the permitted scalar types. If you open up a console, and initialize a params object in this shape:
params = ActionController::Parameters.new screenshot: { title: "afa", assets_attributes: {"0" => {filename: 'a string'}}}
and then run it against your last line:
p = params.require(:screenshot).permit(:title, assets_attributes: :filename)
# => {"title" => "afa", "assets_attributes"=>{"0"=>{"filename"=>"abc"}}}
However, if you do the same against a params hash with the uploaded file, you get
upload = ActionDispatch::Http::UplaodedFile.new tempfile: StringIO.new("abc"), filename: "abc"
params = ActionController::Parameters.new screenshot: { title: "afa", assets_attributes: {"0" => {filename: upload}}}
p = params.require(:screenshot).permit(:title, assets_attributes: :filename)
# => {"title" => "afa", "assets_attributes"=>{"0"=>{}}}
So, it is probably worth a bug or pull request to Rails, and in the meantime, you will have to directly access the filename parameter using the raw params object:
params[:screenshot][:assets_attributes]["0"][:filename]
So, you're dealing with has_many forms and strong parameters.
This is the part of the params hash that matters:
"assets_attributes"=>{
"0"=>{
"filename"=>#<ActionDispatch::Http::UploadedFile:0x00000004edbe40
#tempfile=#<File:/tmp/RackMultipart20130123-18328-navggd>,
#original_filename="EK000005.JPG",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"screenshot[assets_attributes][0][filename]\"; filename=\"EK000005.JPG\"\r\nContent-Type: image/jpeg\r\n">
}
}
when you define strong parameters like this...
permit(:assets_attributes => [:filename])
Things break, because where rails expects a filename it's getting this "0"
What does that number mean? It's the id for the asset you are submitting via your form. Now initially you might think you have to do something like
permit(:assets_attributes => [:id => [:filename]])
This looks like it follows other strong parameters syntax conventions. However, for better or for worse, they have made things a little easier, and all you have to write is:
permit(:assets_attributes => [:asset_id, :filename])
Edit -
As jpwynn pointed out in the comments, in Rails 4.2.4+ the correct syntax is
permit(:assets_attributes => [:id, :filename])
and that should work.
When you hit walls with strong params, the best thing to do is throw a debugger in your controller and test things out. params.require(:something).permit(:other_things) is just a method chain so you can try out different things on the full params hash until you find what works.
try
def screenshot_params
params.require(:screenshot).permit(:title, :assets_attributes => [:filename, :id, :screenshot_id])
end
I had this issue about a month ago and some searching around dug up this solution. It was adding the :id or :screenshot_id that fixed the problem (or both, I can't remember). This works in my code though.
Actually there is a way to just white-list all nested parameters.
params.require(:screenshot).permit(:title).tap do |whitelisted|
whitelisted[:assets_attributes ] = params[:screenshot][:assets_attributes ]
end
This method has advantage over other solutions. It allows to permit deep-nested parameters.
While other solutions like:
params.require(:screenshot).permit(:title, :assets_attributes => [:filename, :id, :screenshot_id])
Don't.
Source:
https://github.com/rails/rails/issues/9454#issuecomment-14167664
I had same problem just got it fixed now all you have to do is
params.require(:vehicle).permit(:user_id, assets_attributes: [:id, :image]).
Use pry gem to see what kind of attributes your asset object has makes sure theres an id and add other missing attribute, that should then work perfectly.
Am using paperclip assets is my nested object inside the vehicle class and an attachment of images is added to the asset.
make sure you do the validation in the model
accepts_nested_attributes_for :assets, allow_destroy: true
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
In your view loop through the asset to get each image
<%= #vehicle.assets.size %>
<% for asset in #vehicle.assets %>
<%=link_to image_tag (asset.image.url(:thumb)) %>
<% end %>
If am correct your problem is that asset_attributes is an array with each image having an index column and an image
Your form_for should have something similar to this and if you want you can also include preview so the upload can view their images use the bottom code for that
<div class="field">
<h3>Vehicle Image Upload</h3>
<%= f.fields_for :assets do |asset_fields| %>
<% if asset_fields.object.new_record? %>
<p>
<%= asset_fields.file_field :image %>
</p>
<% end %>
<% end %>
</div>
<div class="field">
<h4>Vehicle Image</h4>
<%= f.fields_for :assets do |asset_fields| %>
<% unless asset_fields.object.new_record? %>
<%= link_to image_tag(asset_fields.object.image.url(:thumb)),
asset_fields.object.image.url(:original)%>
<%= asset_fields.check_box :_destroy %>
<% end %>
<% end %>
</div>
Sanitize before save in controller Sanitize accepts_nested_attributes_for attributes with index.
before_action :sanitize_fields_params, :only => [:create, :update]
def sanitize_fields_params
product_free_shippings_attributes = params[:product][:product_free_shippings_attributes]
product_free_shippings_attributes.each do |index, key_value|
params[:product][:product_free_shippings_attributes]["#{index}"][:weight] = clear_decimal(key_value[:weight])
params[:product][:product_free_shippings_attributes]["#{index}"][:height] = clear_decimal(key_value[:height])
params[:product][:product_free_shippings_attributes]["#{index}"][:width] = clear_decimal(key_value[:width])
params[:product][:product_free_shippings_attributes]["#{index}"][:depth] = clear_decimal(key_value[:depth])
end
end
def clear_decimal(field)
return (field.to_s.gsub(/[^\d]/, '').to_d / 100.to_d) unless field.blank?
end

How can I format the value shown in a Rails edit field?

I would like to make editing form fields as user-friendly as possible. For example, for numeric values, I would like the field to be displayed with commas (like number_with_precision).
This is easy enough on the display side, but what about editing? Is there a good way to do this?
I am using the Rails FormBuilder. Upon investigation, I found that it uses InstanceTag, which gets the values for fields by using <attribute>_value_before_type_cast which means overriding <attribute> won't get called.
The best I have come up with so far is something like this:
<%= f.text_field :my_attribute, :value => number_with_precision(f.object.my_attribute) %>
Or my_attribute could return the formatted value, like this:
def my_attribute
ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end
But you still have to use :value
<%= f.text_field :my_attribute, :value => f.object.my_attribute %>
This seems like a lot of work.
I prefer your first answer, with the formatting being done in the view. However, if you want to perform the formatting in the model, you can use wrapper methods for the getter and setter, and avoid having to use the :value option entirely.
You'd end up with something like this.
def my_attribute_string
foo_formatter(myattribute)
end
def my_attribute_string=(s)
# Parse "s" or do whatever you need to with it, then set your real attribute.
end
<%= f.text_field :my_attribute_string %>
Railscasts covered this with a Time object in a text_field in episode #32. The really clever part of this is how they handle validation errors. It's worth watching the episode for that alone.
This is an old question, but in case anyone comes across this you could use the number_to_X helpers. They have all of the attributes you could ever want for displaying your edit value:
<%= f.text_field :my_number, :value => number_to_human(f.object.my_number, :separator => '', :unit => '', :delimiter => '', :precision => 0) %>
There are more attributes available too: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html
If you want a format to be created or maintained during editing, you will need to add Javascript to implement "masks." Here is a demo.
It was the first hit in these results.
You can use the number_format plugin. By specifying a number_format for an existing numeric attribute inside your model, the attribute will now appear as formatted to Rails in all forms and views. It will also be parsed back from that format (when assigned via forms) prior to insertion into the database. (The plugin also creates purely numeric unformatted_<attribute-name> accessors which can continue to be used for arithmetic, or for direct numerical assignment or retrieval by you for seamless integration.)
class MyModel < ActiveRecord::Base
# this model has the balance attribute, which we
# want to display using formatting in views,
# although it is stored as a numeric in the database
number_format :balance,
:precision => 2,
:delimiter => ',',
:strip_trailing_zeros => false
def increment_balance
unformatted_balance += 10
end
You can also combine the above with a Javascript solution, which can force the user to maintain the decimal point and thousands separators in place while editing, although this is really not necessary.
I have done something similar. We format times and lengths using a custom form builder. It makes use of the existing text_field, but wraps it so the value can be customized:
class SuperFormBuilder < ActionView::Helpers::FormBuilder
include ApplicationHelper
include FormHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::FormTagHelper
def length_field(label,*args)
scale = 'medium'
args.each do |v|
if v.has_key?(:scale)
scale = v[:scale]
v.delete(:scale)
end
end
value = length_conversion(#object.send(label.to_sym),scale)
options = (args.length > 0) ? args.pop : {}
return has_error(label, text_field_tag(field_name(label),value,*args) + ' ' + length_unit(scale))
end
private
def field_name(label)
return #object_name + "[#{label}]"
end
def has_error(label, output)
return "<div class='fieldWithErrors'>#{output}</div>" if #object.errors[label]
return output
end
And it is used like this:
<%= form_for( #section, {:action => 'save', :id => #section.id}, :builder => SuperFormBuilder) do |sf| %>
<%= sf.length_field :feed_size_min_w, :size => 3, :scale => 'small' %>
<% end %>
The end result is a value in the appropriate unit based off their choice on system (Metric, Imperial) and scale IE small = inches or millimeters.
I basically copied the text_field method from the existing form builder, which uses the text_field_tag itself.
There are two gotchas: 1) Knowing the name of the object field and how to access the object to get the value which you want to format. 2) Getting the name right so when the form is submitted it is part of the correct params hash.
The form builder is given a class variable #object. You can get the value of the field using the .send method. In my case I send the label :feed_size_min_w to the #object and get its length back. I then convert it to my desired format, and give it to the text_field_tag.
The name of the field is key to having it end up in the params hash, in my instance the params[:sections] one. I made a little helper function called field_name that takes care of this.
Finally the has_error wraps the field in an error div if there are errors on that label.
I needed "nicer" format on some specified text fields, resolved it by adding this to my initializers. Seems to work nicely on Rails ~= 5.2 and it should be easy to customize.
class ActionView::Helpers::Tags::TextField
private
def value_before_type_cast # override method in ActionView::Helpers::Tags::Base
v = super
# format as you like, when you like
if #options.delete(:nice_decimal)
v = v.to_s.gsub('.', ',') if v.is_a?(BigDecimal)
end
v
end
end
Usage in form f
<%= f.text_field :foo, nice_decimal: true %>

Resources