简体   繁体   中英

'validate_inclusion_of' isn't working

I need to set a condition where, if my_counter is equal to 0 , 1 or 2 , then my validation flag is set to true , otherwise set my validation flag to false .

But my validate_inclusion_of call isn't working:

if User.find_by_email(@email)
      user = User.find_by_email(@email)
      user.my_count += 1
      user.save

      # Here is where it fails
      if validates_inclusion_of :my_count, :in => [0,1,2]
        @my_flag = true
      else
        @my_flag = false
      end

That is not how you setup validations on models. May I suggest you do this:

@my_flag = [0,1,2].include? user.my_count

Edit: let me point out that you are finding your User twice which results in 2 queries. Consider doing this:

if user = User.find_by_email(@email)
  user.my_count += 1
  user.save
  @my_flag = [0,1,2].include? user.my_count
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM