Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rails active record attributes corresponding SQL values

If I have some activerecord object, is there a way to get the corresponding SQL values that will be inserted to the database before saving the record? That is for example if there is a column of type datetime, then it will be converted to some string format, also a json attribute will be serialized, so is there a way to know these values in advance?


1 Answers

I think I found it :)

First get the value for the database, then quote it.

Assume we have a book model: Book(title,published_at,...)

book = Book.new(title: "Some title", published_at: Time.now)
value_for_database = book.instance_eval("@attributes")["published_at"].value_for_database
quoted_value = Book.connection.quote(value_for_database)

quoted_value now contains the sql value I need :)


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!