views:

15

answers:

1

Hi,

I have this strange SQL error when I try to know wether an object is in an array:

@announcement = Announcement.first
puts "YAY" if current_user.announcements_read.include?(@announcement)

Error:

ActiveRecord::StatementInvalid (SQLite3::SQLException: ambiguous column name: created_at: SELECT "announcements".id FROM "announcements" INNER JOIN "readings" ON "announcements".id = "readings".announcement_id WHERE ("announcements"."id" = 3) AND (("readings".user_id = 1)) ORDER BY created_at DESC LIMIT 1)

(the middle table between users and announcements is readings, and it works perfectly when I do something like user.announcements_read.include?(announcement) in the console)

But it works when I do the opposite request:

puts "YAY" if @announcement.read_by.include?(current_user)

What is going on here? Why does the first request work in the console but not in the app? Why do current_user.announcements_read.include? gets an SQL error when user.announcements_read doesn't?

Kevin

A: 

I'm guessing announcements_read is a named scope, with an :order clause which looks something like :order => "created_at". It's ambiguous because the created_at column is in more than one table in the query. Fixing it should be straightforward -- the order clause is a SQL fragment, so you should be able to prefix created_at with the appropriate table name.

As to why the other methods don't generate an error, perhaps you have different environments? Can you look at the logs to see what queries are being generated?

zetetic