开发者

ActiveRecord None Key Association

开发者 https://www.devze.com 2023-03-08 16:03 出处:网络
I have two tables/models (User, Demographic) which have a loose relationship and share a common column (email). There could be more than one User record with the same email, but there would onl开发者_

I have two tables/models (User, Demographic) which have a loose relationship and share a common column (email). There could be more than one User record with the same email, but there would onl开发者_JAVA百科y be a single demographic record.

Is it possible to define a has_one and has_many relationship and force it to use the email column for the join instead of id?

Thanks, Scott

P.S. If it matters, I am using ActiveRecord 3.x


You can't use non-unique data as a key as there is nothing to enforce which instance of the email address the resource belongs to. You can use the email as a foreign key though, but it will return the demographic for all users with that email address.

To override the foreign key do:

  belongs_to :user, :foreign_key => 'email'

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

0

精彩评论

暂无评论...
验证码 换一张
取 消