0

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!!

1
  • What have you tried so far? There are a few ways to approach this. And, if they are always locked, do you need two columns? Commented Mar 13, 2017 at 17:11

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
try self.description == 1 ? "yes" : "no"
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.