Rails Simple Form Default Value if Submitted Nil - ruby-on-rails

I need to overwrite any blank field submissions in my simple form with the text value "N/A". I've found how to set a default value beforehand, but I would like the field left blank for users to fill out and submit, and only changed if they leave it blank. Is this possible? Thanks!

<%= f.input :survey_year, :input_html => { :value => 'N/A'} %>
Should do the trick. See the flipflops.org link in my comment above for alternative approaches.

Try to the following
before_save :default_values
def default_values
self.name ||= 'N/A' #=> note self.name = 'N/A' if self.name.nil?
end
When a user submits a form with blank/nil name then it will submit to "N/A" otherwise none

Related

Rails: Only update attribute when specified in form

I have a form, in which users can add their birthday. Now currently, whenever someone submits this form, he will add a birthday, as the date input always has a value.
Is there a way I can add a checkbox - and only if it is checked, the birthday should be saved to the record? If the checkbox is not checked though, the current value for birthday should be removed.
= simple_form_for resource, as: resource_name, url: registration_url(resource_name) do |f|
= f.input :another_field
= f.input :birthday_set?, as: :boolean # or something else?
= f.input :birthday
= f.input :submit
In the controller, you could do something like:
def create
user = User.new
user.birthday = params[:user][:birthday_set?] ? params[:user][:birthday] : nil
params[:user].delete(:birthday, :birthday_set?)
user.update_attributes(user_params)
...
end
And just remove the :birthday / :birthday_set? keys from the permit element of your params.
I'd look at moving :birthday_set? into a form_tag field so it sits outside of params[:user] and then you won't have to worry about clearing it from the params. If you're not storing it in the db, this makes more sense anyway.
This will avoid unpermitted parameters being thrown, and do exactly what you're after.
You could also look into disabling the :birthday field in the front end using js when the checkbox is toggled, but would still want to handle this regardless.
Personally, I'd go down #atomAltera's route and use an attr_accessor and before_save, but if you want to avoid that, this approach will work.

Rails: how to get fields of rejected submit form?

I got one big form with many fields. There are multiple select_tag fields:
-(0..2).to_a.each do |id|
= select_tag('product[category_ids][]', options_from_collection_for_select(Category.all, :id, :name), :prompt=> '-- Select a Category --')
Problem: If the form is rejected upon submit, the :new action does not remember what is the previous selected values of select_tags.
Every other field reappears after submit (like :title, :description), but categories_id are lost.
Probable solution: We must add default selection to the select_tag in the options_from_collection_for_select method. How to get that category_id value? How can we access the fields of the previous form?
options_from_collection_for_select(Category.ordered, :id, :name, category_id)
You could store this data in the session and load it in the new action if it exists and clear that from the session.
That way anytime the fields reject the one that is not remembered loads into the session and is loaded into the select on the new action. Otherwise nothing is loaded when this session variable is blank.
Hope this helps.
In my form
#product.categories = []
but
#product.category_ids = [1,42,57]
So I added one messy if statement:
-if #product.category_ids.count == 0 #create new product
-(0..2).to_a.each do |id|
= select_tag('product[category_ids][]', options_from_collection_for_select(Category.all, :id, :name), :prompt=> '-- Select a Category --')
-else #edit old product, or fixing errors to previous submit
-#product.category_ids.each do |category_id|
= select_tag('product[category_ids][]', options_from_collection_for_select(Category.all, :id, :name, category_id), :prompt=> '-- Select a Category --')

Change default population string for form field

I'm building a form on ROR4, using the simple_form gem, to modify my user's data. The thing is that my database is normalized to have the user's first and last name in lower case. So I have the following in my User model:
before_save :lowercase_names
def lowercase_names
self.first_name.downcase!
self.last_name.downcase!
end
But of course when I populate my upadate form with the user object I get the following:
First name: carlos
Last name: ledezma
I was wondering if there is a way to override this behavior so Rails would print instead:
First name: Carlos
Last name: Ledezma
That is, the titleized version of the fields.
Thanks in advance for the help
In your form set the value to titleized name
=f.input :first_name, :value => #user.first_name.titleize
The above line will vary depending on if you are using simple form or not. But it will give you the basic idea. You are overwriting the value of the input field
If you want it to be changed everywhere, then override getter for first_name and last_name
def last_name
self.read_attribute(:last_name).titleize
end
def first_name
self.read_attribute(:first_name).titleize
end
Be aware that this will titleize your first name and last name everywhere you call the getter
Try using the value attribute of the text_field helper in your form to set the shown value as the capitalized first and last name:
<%= f.input :first_name, :value => f.object.first_name.capitalize %>
<%= f.input :last_name, :value => f.object.last_name.capitalize %>
Updated
Also, you can override getter method in User model like:
def first_name
self.read_attribute(:first_name).capitalize
end
def last_name
self.read_attribute(:last_name).capitalize
end

Rails: Optional lookup fields

In my Rails app I am using collection_select to provide a list of valid choices for the user. I stored only the id from the looked-up table. I then make a call to the looked-up class in the show view to retrieve the actual value for the id.
in edit:
= f.collection_select :language_id, Language.find(:all, :conditions => ["supported = 't'"]), :id, :language, include_blank: false, :prompt => "Language"
in show:
%p
%b Language:
= Language.find(#article.language_id).language_code
This is all working fine unless no choice is made. If the #article.language_id field is null, the view cannot load as the find fails. Any suggestions on how to ignore null values and leave the field blank?
using find_by_id would be an option, as it does not raise an error if the id could not be found.
this issues a call to the database though.
so i would just check the languange_id and provide a default
= #article.language_id.nil? ? default : Language.find_by_id(#article.language_id)
this could also be moved into the model or a helper, so that it does not clutter your view code.
This is a common problem. Simply use try to leave nil values:
if #article.try(:language_id) != nil
#code = Language.find(#article.language_id).language_code
else
//default nil
#code = nil
end

Accept Rails model attribute only if it was previously blank

I have a Rails model (persisted with Mongoid) that can be collaboratively edited by any registered user. However, I want to allow editing any particular attribute only if it was previously blank or nil.
For example, say someone created an object, and set its title attribute to "Test Product". Then another user comes along and wants to add a value for price, which until now has been nil.
What's the best way to do this, while locking an attribute that has previously been entered?
Look into the ActiveRecord::Dirty module for some nice utility methods you can use to do something like this:
NON_UPDATABLE_ATTRIBUTES = [:name, :title, :price]
before_validation :check_for_previously_set_attributes
private
def check_for_previously_set_attributes
NON_UPDATABLE_ATTRIBUTES.each do |att|
att = att.to_s
# changes[att] will be an array of [prev_value, new_value] if the attribute has been changed
errors.add(att, "cannot be updated because it has previously been set") if changes[att] && changes[att].first.present?
end
end
The easiest way, i think, is by checking for it in the form itself.
Just say add :disabled => true to the input field if the person cannot edit it.
<% if #my_object.name %>
<%= f.text_field :name, :disabled => true %>
<% else %>
<%= f.text_field :name, :disabled => true %>
<% end %>
(i think there is a prettier way to write this code)
But by using this the user has a visual feed back that he can't do something, it is always better to not allor something than to give an error message

Resources