如果在rails查询中自定义select,如何定义类型?



我的查询是这样的:

@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("posts.*, read_marks.comments_cache as rm_comments_cache, read_marks.timestamp as last_read_at")

但是当我调用@posts.each{|post| post.last_read_at}时,它返回一个字符串而不是日期时间。

为什么不尝试使用ReadMark模型呢?

@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}

这个方法更简洁,并且按照设计的方式使用了ActiveRecord。

如果你真的想使用原来的查询,你可以手动解析日期。

@posts.each{|post| Date.parse post.last_read_at }

即使last_read_at应该是datetime ActiveRecord不自动反序列化非列值。您必须自己解析日期时间。

@posts.each{|post| post.last_read_at = Time.zone.parse(post.last_read_at)}

最新更新