tags:

views:

24

answers:

2

There is a model relation like this.

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

My question is : the A has a attribute named flag, now i want to create a function like this:

if flag == 1, I want the class A like this belongs_to :ref_config,:class_name => 'Department and if flag == 2, i want the class A like this belongs_to :ref_config,:class_name => 'User'

How can I implement the function

Thank you!

+2  A: 

Have a look at polymorphic associations, which will let you use the same belongs_to relation to refer to different models.

You could configure your models something like this:

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

To set up the needed columns in the A table, use a migration like this:

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
Pär Wieslander
But i have a additional request, i have two object related the user model ,one is know_user ,the other is unknow_user
Small Wolf
A: 

From the little i got your question following may help you.

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