简体   繁体   中英

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?

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 :)

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