ActiveRecord未知列

时间:2012-12-09 16:33:36

标签: ruby activerecord has-many-through mysql2

我遇到了一个小问题我有一个has_many通过关系这里是模型的代码

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

现在在控制台我可以输入u = User.first,然后输入u.friendships.first.following这给了我第一个跟随你的用户,但是当我输入u.friendships.last.following时我得到这个错误< / p>

来自u.friendships.first.following的SELECT语句

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

和来自u.friendships.last.following的SELECT语句

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

如果我再运行u.friendships然后u.friendships.last.following,我再也不会收到错误了,为什么会这样?

1 个答案:

答案 0 :(得分:1)

直接来自 Rails 3.2.9 / postgresql 上的代码的friendships的sql输出:

# 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 1

因此,出于某些原因,我id会自动选择ORDER BY "friendships"."id"并且它有效。也许您的问题与您的数据库有关?

#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 
);