activerecord查找关联模型的条件

时间:2010-09-19 18:25:09

标签: ruby-on-rails activerecord associations

所以我没有找到很多关于在相关模型的activerecord find方法上使用条件的文档,但我找到了各种各样的例子。虽然它们似乎都不适合我。

user has_one avatar
avatar belongs_to user

Avatar.find(:all, :include => :user, :conditions => {:user => {:login => 'admin'}})

返回可笑的长错误

SQLite3::SQLException: no such column: user.login: SELECT "avatars"."id" AS t0_r0, "avatars"."user_id" AS t0_r1, "avatars"."featured" AS t0_r2, "avatars"."avatar_file_name" AS t0_r3, "avatars"."avatar_content_type" AS t0_r4, "avatars"."avatar_file_size" AS t0_r5, "avatars"."created_at" AS t0_r6, "avatars"."updated_at" AS t0_r7, "users"."id" AS t1_r0, "users"."login" AS t1_r1, "users"."email" AS t1_r2, "users"."crypted_password" AS t1_r3, "users"."password_salt" AS t1_r4, "users"."persistence_token" AS t1_r5, "users"."perishable_token" AS t1_r6, "users"."login_count" AS t1_r7, "users"."failed_login_count" AS t1_r8, "users"."last_request_at" AS t1_r9, "users"."current_login_at" AS t1_r10, "users"."last_login_at" AS t1_r11, "users"."current_login_ip" AS t1_r12, "users"."last_login_ip" AS t1_r13, "users"."created_at" AS t1_r14, "users"."updated_at" AS t1_r15 FROM "avatars"  LEFT OUTER JOIN "users" ON "users".id = "avatars".user_id WHERE ("user"."login" = 'admin') 

我尝试过各种其他模式,包括

:conditions => "user.login == 'admin'"

但没有任何效果。

这是使用rails 2.3.8应用程序,但也安装了rails3。所以我有activerecord 3.0.0& 2.3.8安装。我认为这可能是一个问题,但似乎不太可能。

2 个答案:

答案 0 :(得分:2)

而不是

:user => {:login => 'admin'}

:users => {:login => 'admin'}

用户的取值

答案 1 :(得分:1)

数据库本身中表名的标准Rails格式是“全小写,复数”。

因此,您可以调试SQL错误并查看:

no such column: user.login

由于我们知道表名是“用户”,问题是你引用表“user”

修复取决于Active Record的版本。我更喜欢旧学校,因为它更清楚条件子句是SQL,而不是Ruby / Rails:

Avatar.find(:all, :include => :user,
  :conditions => "users.login = 'admin'")

注意:Rails 3与上述不同......

添加了:

请记住,如果您正在查找作为用户参数提供的登录信息,则必须正确转义参数。 Rails让这很容易:

user_login = "admin"  # or, for example, params['user']
Avatar.find(:all, :include => :user,
  :conditions => ["users.login = ?", user_login])