【发布时间】:2012-01-14 11:55:33
【问题描述】:
我有一个旧数据库。用户有很多账户,账户有很多用户。有一个名为 UserAccountMapping 的连接表:
=====================
|UserID | AccountID|
=====================
两列都是 var chars 类型。
在 Account.rb 中:
has_and_belongs_to_many :users, :join_table => :UserAccountMapping, :foreign_key => :AccountID, :association_foreign_key => :UserID
在 User.rb 中:
has_and_belongs_to_many :accounts, :join_table => 'UserAccountMapping', :foreign_key => :UserID, :association_foreign_key => :AccountID
用户还有一个 :email 和 :id 列。用户的主键是 :id (整数), :email 是字符串。
当我执行User.first.accounts 之类的操作时,连接 SQL 的 WHERE 子句将尝试将 UserAccountMapping.UserID 与用户的 :id 匹配,但我希望它使用用户的 :email。这可能吗?
所以,它生成的 SQL 是:
SELECT "Account".* FROM "Account" INNER JOIN "UserAccountMapping" ON "Account"."AccountID" = "UserAccountMapping"."AccountID" WHERE "UserAccountMapping"."UserID" = 3
相反,我想要这个:
SELECT "Account".* FROM "Account" INNER JOIN "UserAccountMapping" ON "Account"."AccountID" = "UserAccountMapping"."AccountID" WHERE "UserAccountMapping"."UserID" = "user@something.com"
【问题讨论】:
-
您为什么要这样做?尝试设置
User主键 => :email
标签: ruby-on-rails ruby