问题
This problem seems fairly simple, but I've never encountered one like this.
Here are the settings:
Post has_many :reader_links
Post has_many :readers, :through => :reader_links
I need to find out if there are readers reading a post.
@post.reader_links.where('created_at >= ?', 45.minutes.ago).any?
Works great.
@post.readers.where('created_at >= ?', 45.minutes.ago),any?
throws an ambiguous table column error because it's confused whether the created_at
column means that of reader object or reader_link object. This happens because the class of a reader is actually User. How do I query readers who were created by reader_links 45 minutes ago?
I'm looking for something like..
@post.readers.where('reader_link.created_at >= ?', 45.minutes.ago)
回答1:
If I get it right, you just need to specify which created_at
column you're talking about:
@post.readers.where('reader_links.created_at >= ?', 45.minutes.ago).any?
回答2:
You coul merge the scopes to get rid of ambigious errors, so each scope has it's own visibility range.
using meta_where
:
Post.scoped & (ReaderLink.scoped & User.where(:created_at.gt => 45.minutes.ago))
without meta_where
:
Post.scoped.merge(ReaderLink.scoped.merge(User.where('created_at >= ?', 45.minutes.ago))
This will result in arrays of Post
objects containing the reader_links and readers data for all readers younger than 45 minutes. Please try it in the rails console.
Edit: for a single post
post_with_fresh_users = Post.where('id = ?', some_id).merge(ReaderLink.scoped.merge(User.where('created_at >= ?', 45.minutes.ago))
Edit: all fresh readers of a post (different order)
fresh_readers_for_post = User.where('created_at >= ?', 45.minutes.ago).merge(ReaderLink.scoped.merge(Post.where('id = ?', @post.id))
How it works:
http://benhoskin.gs/2012/07/04/arel-merge-a-hidden-gem
来源:https://stackoverflow.com/questions/15846517/ambiguous-table-reference