I've got a table called "Customers". The table can be seen here. "description" is string while "fruit" is integer. "fruit" will not be displayed to a user when filling in the table. Instead, I want ruby to automatically assign the value "0" to the "fruit" column if the corresponding answer for "description" is "yes". So if a user selects yes, the table shall automatically generate a 0 in the fruit column and if the user selects no, it shall automatically generate a 1 in the column... Any ideas?? Thank you in advance!!
2 Answers
Add before_save filter in User Model
user.rb
class User < ActiveRecord::Base
before_save :assign_fruit
private
def assign_fruit
self.fruits = (self.description == "yes" ? 1 : 0 )
end
end
2 Comments
Krawalla
If I wanted to do it the other way around... if i wanted to turn a "1" into a "yes".. I tried this:
def assign_test self.test = (self.description == "1" ? "yes" : "no" ) end Now, whether i put in a 1 or a 0 or whatever else, it returns a "no" in the table... can you help?puneet18
try self.description == 1 ? "yes" : "no"
your question is kind of vague - please provide more details.
How does the user input yes/no?
Is it by submitting a form to update or create? If so you could write something like this in the action
if params[:answer]
instance.update_attribute(fruit, true)
end
If you are trying to accomplish this in a show page (let's say by clicking a checkbox)
you could achieve this with jQuery i.e.
$('.checkbox_selector/.select_box_selector').on('change', function() {
// ajax the boolean
});
I will need more information to respond with a less generic answer anyway hope this helps
i would also recommend setting fruit as a boolean and not an integer.