1

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

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 我得到这个错误

来自 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 ,我不再收到错误,这是为什么呢?

4

1 回答 1

1

这是我的 sql 输出friendships,直接来自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 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 
);
于 2012-12-09T20:01:49.793 回答