Rails 3 - how to save (un)checked checkboxes? - ruby-on-rails-3

I have in a form (form_tag) several checkboxes like this:
<%=check_box_tag 'model_name[column_name]', 1, (#data.model_name.column_name == 1 ? true : false)%>
And updating them like:
variable = ModelName.find(params[:id])
variable.update_attributes(params[:model_name])
This works only in a moment, when I check some checkboxes - send them and they will be saved. That's fine.
But when I uncheck all checkboxes - send form - so nothing happend, in the DB table will not set the value 0 in the columns...
Could you give me any tip, how to fix it?
Thank you in advance

This happens because an unchecked checkbox will not send any value to the server. To circumvent this Rails provides the check_box helper, which generates code like this:
<input type="hidden" name="model[attr]" value="0" />
<input type="checkbox" name="model[attr]" value="1" />
Alternatively, insert a hidden field with hidden_field_tag:
<%= hidden_field_tag 'model_name[column_name]', '0' %>
<%= check_box_tag 'model_name[column_name]', 1, (#data.model_name.column_name == 1 ? true : false) %>

Related

Rails+simple_form_for Change common id

I want to change form common name in rendering side
_from.html.haml
..
= f.simple_fields_for Image.new do |form|
= render 'avatar_fields', f: form
..
_avatar_fields.html.haml
..
= f.hidden_field :imageable_type
..
This is rendering like
<input id="product_image_imageable_type" name="product[image][imageable_type]" type="hidden">
But i want to render like this
<input id="product_logo_attributes_imageable_type" name="product[logo_attributes][imageable_type]" type="hidden">
I don't want to edit my '_avatar_fields.html.haml' screen. Because it's common html.
Any suggestion please..?
you can do some thing like
...
= f.hidden_field :imageable_type, input_html: {id: 'product_logo_attributes_imageable_type'}
...
I hope that this helps you

Add a custom validation in rails 3

I am working with a nested model a question has multiple answers and only one can be marked as correct how can i validate to check that only one question was marked as correct. The correct is a boolean field.
#question model
validate :one_correct_answers
def one_correct_answers
if self.choices.correct_choices > 1
errors.add(:base, "please select only one correct answer")
end
end
In Question model
class Question
has_many :choices
accepts_nested_attributes_for :choices, :reject_if => ->(choice){ choice[:value].blank? }
validate :only_one_correct_answer
private
def only_one_correct_answer
unless (choices.select{ |choice| choice.correct }.size == 1)
errors.add(:choices, "You must provide only 1 correct answer")
end
end
end
In Form HTML
<input name="question[choices_attributes][0][correct]" type="checkbox">
<input name="question[choices_attributes][1][correct]" type="checkbox">
<input name="question[choices_attributes][2][correct]" type="checkbox">
<input name="question[choices_attributes][3][correct]" type="checkbox"> ... till n
and in QuestionsController
#question = Question.new(params[:question])
#question.valid? => will automatically call Question#only_one_correct_answer and add errors,if any.
I hope, this will help you. :)
First, your checkboxes should look like this:
<input id="something_" name="something[]" type="checkbox" value="<%= some_id %>">
This way, when you submit the form, the params should look like and array of the checked checkboxes:
params: something => [1, 2]
Then, on your controller you set the variable correct_choices to this array, and validate with your custom validator.

how refer to values from form_tag?

Like in title - I've got a tag (no model) based form (form_tag) and I want after submit obtain values entered in fields of that form - how can I do it?
When a form is submitted, such as the one below:
<% form_tag do %>
<label for="first_name">First Name:</label>
<%= text_field_tag :first_name %>
<% end %>
a params hash is set so you can easily access its values in your controller, like so:
value = params[:first_name]
Just use the params hash in the controller, like so:
def update
field_value = params[:field_name_here]
end

Giving 'TemplateError' can't convert String into Integer

I recently transfered my app from Rails2 to Rails3.
The code in 'app/views/distribution/index.html.erb' is like :-
<div style="padding-bottom:10px; padding-left:0px;float:left;display:<%= (!session[:album][#artist.id.to_s].empty? && !session[:album][#artist.id.to_s].nil?)?'block' : 'none' %>" id = "make_payment_enabled">
<%= link_to 'Make Payments',{:action => 'pay', :album=>#album.id}, :class => "button" %>
</div>
It's giving me TemplateError on line :-
<div style="padding-bottom:10px; padding-left:0px;float:left;display:<%= (!session[:album][#artist.id.to_s].empty? && !session[:album][#artist.id.to_s].nil?)?'block' : 'none' %>" id = "make_payment_enabled">
How to resolve the problem ?
Solution 1: In the ERB tag, try putting spaces around the 'or' question mark, i.e. ....nil?) ? 'block....
Solution Better: Do step one, then put that code in a helper. Will really help to clean up your views.
UPDATE:
A few other tips: you will want to switch the order of the conditions, because you will want to see if the value is nil before checking if it's an empty string.
Calling obj.blank? is the equivalent of calling obj.nil? && obj.empty?, so that could make the code a bit shorter. Even better, obj.present? is the same as !obj.blank?.
Therefore, that line could be simplified to:
session[:album][#artist.id.to_s].present? ? 'block' : 'none'
Happy Rails-ing!

Rails 3 - select_tag helper - Blank option tag

I have a select_tag populated from a #users array that I'm using to perform searches. When the user first lands on the page, I'd like it to display a blank or custom tag, rather than the first item in the array?
Is this an option using the select_tag helper? To insert a blank "" option?
My helper so far:
<%= select_tag :search_user, options_from_collection_for_select(#users, "id", "name"), :class => 'submittable'%>
You can use the option :include_blank => true as documented here.
I think the right way is
:prompt=>"your text"
So, rather than using the options_from_collections_for_select method, I was able to insert an item into my array using the options_for_select. Compared to my above code, I inserted "everyone" in the below snippet.
<%= select_tag :search_user, options_for_select(#users.collect{ |user| [user.name, user.id] }.insert(0,"Everyone")), :class => 'submittable'%>
Ruby on Rails 4.0.4 ActionView::Helpers::FormOptionsHelper
:prompt - set to true or a prompt string. When the select element
doesn't have a value yet, this prepends an option with a generic
prompt – “Please select” – or the given prompt string.
select(“post”, “person_id”, Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
could become:
<select name="post[person_id]">
<option value="">Select Person</option>
<option value="1">David</option>
<option value="2">Sam</option>
<option value="3">Tobias</option>
</select>