2011-07-21 42 views
1

我的查询看起来像这样选择:你如何定义类型,如果你自定义的轨道查询

@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}返回一个字符串,而不是日期时间。

回答

1

为什么不尝试使用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 }

+0

但是为什么OP的使用'select'的方法不会将'last_read_at'作为'Datetime'返回? – Zabba

+0

我只想返回所有帖子,即使它没有在readmarks表中有记录。 where语句被应用于返回的所有记录,因此没有read_marks记录的帖子被删除。这就是我所看到的。我不确定它是否应该这样做。 @Zabba我认为它与使用你的迁移设置类型的activerecord有关。 – jnoh

+0

我暗暗猜测为什么这不起作用,ActiveRecord只转换定义为表中列的db值。当列未被明确定义时,这可能无法完成(或未正确完成)。我会更新我的答案以正确进行连接。 – diedthreetimes

1

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

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