Ambiguous table reference

筅森魡賤 提交于 2019-12-12 03:57:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!