ActiveRecord - Flipping Booleans


On a current project, we have a boolean field which stores whether content is available to view on mobile. This works well in the backend, as I can simply ask the model ‘allow_ios?’ and it returns true or false.

However, the wording of the frontend is "Prevent IOS’ with a button that acts like a checkbox. The problem is, when I come to save this in the database, I need to store the opposite to what was provided.

So “Prevent IOS = true” becomes “allow_ios = false” in the database, and vice versa.

Any suggestions how we might deal with this?

My only thought is to use a virtual attribute on the model, and reference that in the form views. The getter and setter would write the opposite value into the real attribute.



Why not flip the boolean in the database to keep things consistent, i.e. rename the field to prevent_ios?

I agree with @andyw8–I’d rather see consistency between the UI and the database value.

Don’t you love when the answer to “how do I do x?” is “don’t do x”? :smile:

1 Like

Many thanks for your input, @andyw8 and @benorenstein! We decided to make the DB match the UI, which makes a lot of sense.

What I didn’t explain is there are several internal APIs where it makes sense to check whether “if allow_ios?” rather than “unless prevent_ios?”. But I’ll probably just create a custom getter method for that case.