2010-06-02 27 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