开发者

Can two associated models share the same join name?

I have a User model that can acquir开发者_JAVA百科e gift certificates from a CardSignup model they create.

However, I also would like to give out free gift certificates from a seperate model called GiftConversion

My models are set up as so :

User.rb

has_many :conversions, :foreign_key => :converted_by, :class_name => "CardSignup"
has_many :conversions, :foreign_key => :converted_by, :class_name => "GiftConversion"

CardSignup.rb

belongs_to                     :converted_by, :class_name => "User"

GiftConversion

belongs_to                     :converted_by, :class_name => "User"

In this way, what I want to do is type User.find(x).conversions, and it would return both the CardSignup model and the GiftConversion model so long as their foreign_key :converted_by is associated to that user model.

Unfortunately, this doesn't work so properly. Instead the compiler just grabs the later statement. In this case, GiftConversion, and only allows that to be recognized as a User.find(x).conversions.

Does anyone know how I can have the User model share both models under the same name?


You could probably have a custom association which connects both tables with a custom SQL statement using UNION, or something like that, but I don't recommend it since you have two models which represent something pretty similar, but not identical – a great use case for single-table inheritance.

The way I would do it is to have one single table for both CardSignup and GiftConversion and use single-table inheritance to connect the two models, so the common table would include a type column which specifies whether it's a CardSignup or GiftConversion.

See here under "Single Table Inheritance" for more information:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜