0

我試圖估計Rails 3 has-and-belong-to-many關聯(HABTM)中的多態關係。Rails 3 HABTM - 訪問交叉點實體

的交點表(user_favorites)具有下列字段:USER_ID,favorite_id,favorite_class

在用戶類,我已經定義的關係:

has_and_belongs_to_many :favorite_users, :class_name => "User", :join_table => "user_favorites", :association_foreign_key => "favorite_id", :foreign_key => "user_id", :conditions => "user_favorites.favorite_class='User'" 

用於檢索數據,該正常工作。不幸的是,這個定義不會添加我需要的favorite_class'值(在這種情況下爲'User')。

有沒有一種方法,可能使用Arel,在保存記錄之前將favorite_class字段設置爲所需的值?

回答

0

我能夠通過使用來解決問題:INSERT_SQL選項(注意使用單引號的):

:insert_sql => 'INSERT INTO user_favorites (user_id, favorite_id, favorite_type) VALUES (#{id}, #{record.id}, "User")' 
2

has_many通過關聯可能會更好。這是一篇可能有所幫助的文章。它解釋了多態has_many:through關係的問題,並提供了一種解決方法。

http://blog.hasmanythrough.com/2006/4/3/polymorphic-through

這可能是也有幫助:

Polymorphic habtm relationships with Rails/ActiveRecord

+0

感謝您的答覆。 – craig 2011-02-02 00:34:19

+0

+1 habtm不允許加入關聯的額外字段。它經常被視爲已棄用,因爲在第一次需要額外字段時,更改關聯(從habtm到hmt)以及使用它們的代碼是一件痛苦的事情。 has_many:通過允許這些沒有這些主要的mods。 – 2012-03-03 23:53:49

0

您的變體中有SQL注入。按照您的UserFavourites模型更好地利用:

before_save :set_favourite_type 

private 

def set_favorite_type 
    self[:favorite_type] = self.favoritable.class.to_s 
end 

或至少使用參數化查詢,而不是#{}