ActiveRecord unknown column-Collection of common programming errors
I ran into a little problem I have a has_many through relationship here is the code for the models
class User < ActiveRecord::Base
has_many :friendships
has_many :followings, :through => :friendships, :foreign_key => "followed_id"
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :following, :class_name => "User", :foreign_key => "followed_id"
end
now at the console I can type u = User.first and then u.friendships.first.following this gives me the first user u is following, but when I type u.friendships.last.following I get this error
the SELECT statement from u.friendships.first.following
Friendship Load (0.3ms) SELECT `friendships`.* FROM `friendships` WHERE `friendships`.`user_id` = 208 LIMIT 1
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 209 LIMIT 1
and the SELECT statement from u.friendships.last.following
Friendship Load (0.3ms) SELECT `friendships`.* FROM `friendships` WHERE `friendships`.`user_id` = 208 ORDER BY `friendships`.`` DESC LIMIT 1
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'friendships.' in 'order
clause': SELECT `friendships`.* FROM `friendships` WHERE `friendships`.`user_id` = 208
ORDER BY `friendships`.`` DESC LIMIT 1
if I then run u.friendships and then u.friendships.last.following again, I don’t get the error anymore, why is that?
-
Heres my sql output for
friendships, straight from your code on Rails 3.2.9 / postgresql:# u.friendships.first.following Friendship Load (0.9ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = 1 LIMIT 1 # u.friendships.first.following Friendship Load (1.3ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = 1 ORDER BY "friendships"."id" DESC LIMIT 1So for some reason for me,
idis getting picked up automatically inORDER BY "friendships"."id"and it works. Maybe your problem has something to do with your DB?#Statements used to create the db for reproducing this problem CREATE TABLE users (id SERIAL PRIMARY KEY) CREATE TABLE friendships ( id SERIAL PRIMARY KEY, user_id integer followed_id integer );
Originally posted 2013-11-10 00:11:12.