2011-01-06 54 views
0

分配:標題:字符串 權限:USER_ID:整數,subject_class:字符串,subject_id:整數,動作:字符串額外的has_many要求

分配的has_many:權限:foreign_key =>:subject_id 但我怎麼做確定它知道有關subject_class == self.class.to_s的要求?

更新:使用:conditions => {:subject_class =>'Assignment'},如何確保何時執行permissions.new:subject_class也會被設置。

回答

0

這是您要使用(http://wiki.rubyonrails.org/howtos/db-relationships/polymorphic

多態關聯您的作業模式的東西,你會做以下幾點:

has_many :permissions, :as => :subject 

而在你的權限模型,你可以這樣做:

belongs_to :subject, :polymorphic => true 

但是,您需要將subject_class字段重命名爲subject_type才能隱式地工作。當所有這些都完成後,您將擁有從Rails免費索取的所有內容。創建新權限時,您不需要傳遞:subject_type。您可以創建一個像這樣的權限和:subject_type將自動爲您填充:

assignment = Assignment.create(:title => "My Assignment") 
permission = Permission.create(:subject => assignment, :action => "read", :user => current_user) 

- or - 

assignment.permission.create(:user => current_user, :action => "read")