how do you define types if you custom select in a rails query
My query looks like this:
@posts = Post.includes(:last_comment)
.joins("LEFT OUTER JOIN read_marks ON posts.id = read_marks.post_id AND read_marks.user_id = #{user.id}")
.where(:postr_id => postr.id)
.select("post开发者_如何学Pythons.*, read_marks.comments_cache as rm_comments_cache, read_marks.timestamp as last_read_at")
But when I call @posts.each{|post| post.last_read_at}
it returns a string and not a datetime.
Why don't you try using the ReadMark model?
@posts = Post.includes(:read_marks)
.joins("LEFT OUTER JOIN read_marks ON posts.id = read_marks.post_id and read_marks.user_id = #{user.id}")
.where(:postr_id => postr.id)
@posts.each{|post| post.read_marks.timestamp}
This method is cleaner, and uses ActiveRecord in the way it was designed.
If you really want to use your original query, you can parse the date manually.
@posts.each{|post| Date.parse post.last_read_at }
Even though last_read_at
should be a datetime
ActiveRecord does not automatically deserialize non-column values. You'll have to parse the datetime yourself.
@posts.each{|post| post.last_read_at = Time.zone.parse(post.last_read_at)}
精彩评论