2010-06-02 69 views
0

有這樣的模型關係。rails belongs_to哪類可供選擇

class A 
belongs_to :ref_config,:class_name => 'User' 
end 

我的問題是: 的A有一個屬性命名標誌,現在我想創建這樣一個功能:

如果標誌== 1,我想A類這樣belongs_to :ref_config,:class_name => 'Department,如果標誌== 2,我想這樣的belongs_to :ref_config,:class_name => 'User'

A類我如何能實現的功能

謝謝!

回答

2

看看polymorphic associations,它可以讓你使用相同的belongs_to關係來引用不同的模型。

你可以配置你的模型是這樣的:

class A < ActiveRecord::Base 
    belongs_to :ref_config, :polymorphic => true 
end 

class Department < ActiveRecord::Base 
    has_many :as, :as => :ref_config 
end 

class User < ActiveRecord::Base 
    has_many :as, :as => :ref_config 
end 

要設置需要的列在A表,使用這樣的遷移:

class CreateAs < ActiveRecord::Migration 
    def self.up 
    create_table :as do |t| 
     t.string :name # or whatever other attributes A should have 
     t.references :ref_config, :polymorphic => true 
    end 
    end 

    def self.down 
    drop_table :as 
    end 
end 
+0

但我有一個額外的請求,我有兩個對象相關的用戶模型,一個是know_user,另一個是unknow_user – 2010-06-02 09:58:39

0

從小事我收到了你以下問題可能對您有所幫助

class A 
    belongs_to :department_config, :class_name => 'Department', :conditions=> flag= 1 
    belongs_to :user_config, :class_name => 'User', :conditions=> flag= 2 
end