开发者

rails belong_to which class to choose

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 na开发者_运维知识库med 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!


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜