Callbacks are probably the easiest way to deal with it, but I would 
probably use before_validation instead of before_save.

Jarin

On Monday, March 24, 2014 2:11:59 PM UTC-7, Chris Radcliff wrote:
>
> Hi James,
>
> In the past I've generally used a 
> callback<http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html>to 
> make sure the boolean is set before saving:
>
> before_save do 
>   self.completed = false if completed.nil?
> end
>
> I vaguely remember some activerecord magic that can be invoked to use the 
> default you've already defined, but I don't remember what it was.
>
> ~chris
>
>
> On Mon, Mar 24, 2014 at 1:49 PM, James Miller <[email protected]<javascript:>
> > wrote:
>
>> Hi Everyone,
>>
>> Wanted to get some feedback on how you all implement something seemingly 
>> trivial in your Rails apps, validation of boolean fields.
>>
>> Let's say you have a "completed" column in a table of tasks where it 
>> should always be 0 or 1 in the DB (MySQL):
>> add_column :tasks, :completed, :boolean, default: false, nil: false
>>
>> If you do nothing else and create a new record, omitting the "completed" 
>> attribute it will create the record and set that attribute to false, 
>> groovy. Explicitly set it to true, that'll work as expected too.
>>
>> But, if you explicitly set it to nil and save, MySQL adapter is going to 
>> choke on it because the field isn't allowed to be null.
>>
>> So I can add this to the model:
>> validates_inclusion_of :completed, in: [true, false]
>>
>> Now we're validating in the model, but the API seems a little too strict 
>> to me -- if someone passes nil, validation fails -- part of me thinks it 
>> should set it to true if explicitly true, else false -- overriding the 
>> writer with something like:
>>
>> def completed=(completed)
>>   write_attribute(:completed, completed == true)
>> end
>>
>> Just seems like a lot of work for a simple boolean and wanted to see how 
>> you all approach it.
>>
>> Happy Monday!
>>
>> James
>>
>>
>>  -- 
>> -- 
>> SD Ruby mailing list
>> [email protected] <javascript:>
>> http://groups.google.com/group/sdruby
>> --- 
>> You received this message because you are subscribed to the Google Groups 
>> "SD Ruby" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to [email protected] <javascript:>.
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
-- 
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
--- 
You received this message because you are subscribed to the Google Groups "SD 
Ruby" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to