Showing Errors in the Logs

I had some errors occurring in my controller, but it wasn’t displaying in my views.  So I had to figure out how to see what was happening since I didn’t see any messages in the logs that were helpful either.

I found the solution in one of the answers here on Stack Overflow.

By adding this to my controller (it was the creation of a model – @user):

logger.warn("====error==========#{@user.error.full_messages.inspect}============")

This recorded the error in my logs (one of my model validations needed to be changed).

Advertisements

Mass Update / Initialize Database Field

I have a field that I need to mass update and I was looking for an efficient way to update them.  I found it with “update_all”.  By doing:

Model.update_all :field=>value

It will update all of the records to the value you want.  If you want to do it for only certain records, you can use a where clause like so:

Model.where(“foo = ?”, “bar”).update_all :field=>value

Validations for Dates

I searched many times trying to figure out how to validate date of birth in my user model.  Finally, I stumbled on the validates_timeliness gem and it worked great for validating if a user was old enough to join my site.

after installing the gem, i just added the line from the example in my user model:

validates_date :date_of_birth, :before => lambda { 18.years.ago },
                              :before_message => "must be at least 18 years old"

https://github.com/adzap/validates_timeliness

Thank you for making this gem available adzap!