具有代表和条件的活动记录

时间:2021-07-20 20:14:01

Is it possible to use delegate in your Active Record model and use conditions like :if on it?

是否可以在Active Record模型中使用委托并使用以下条件:if on it?

class User < ApplicationRecord
  delegate :company, :to => :master, :if => :has_master?

  belongs_to :master, :class_name => "User"

  def has_master?
    master.present?
  end
end

2 个解决方案

#1


30  

No, you can't, but you can pass the :allow_nil => true option to return nil if the master is nil.

不,您不能,但如果master为nil,您可以传递:allow_nil => true选项返回nil。

class User < ActiveRecord::Base
  delegate :company, :to => :master, :allow_nil => true

  # ...
end

user.master = nil
user.company 
# => nil

user.master = <#User ...>
user.company 
# => ...

Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.

否则,您需要使用委托宏编写自己的自定义方法以获得更复杂的选项。

class User < ActiveRecord::Base
  # ...

  def company
    master.company if has_master?
  end

end

#2


2  

I needed to delegate the same method to two models, preferring to use one model over the other. I used the :prefix option:

我需要将相同的方法委托给两个模型,更喜欢使用一个模型而不是另一个模型。我使用了:prefix选项:

from individual.rb

来自individual.rb

delegate :referral_key, :email, :username, :first_name, :last_name, :gender, :approves_email, :approves_timeline, to: :user, allow_nil: true, prefix: true                                
delegate :email, :first_name, :last_name, to: :visitor, allow_nil: true, prefix: true

def first_name
  user.present? ? user_first_name : visitor_first_name
end

#1


30  

No, you can't, but you can pass the :allow_nil => true option to return nil if the master is nil.

不,您不能,但如果master为nil,您可以传递:allow_nil => true选项返回nil。

class User < ActiveRecord::Base
  delegate :company, :to => :master, :allow_nil => true

  # ...
end

user.master = nil
user.company 
# => nil

user.master = <#User ...>
user.company 
# => ...

Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.

否则,您需要使用委托宏编写自己的自定义方法以获得更复杂的选项。

class User < ActiveRecord::Base
  # ...

  def company
    master.company if has_master?
  end

end

#2


2  

I needed to delegate the same method to two models, preferring to use one model over the other. I used the :prefix option:

我需要将相同的方法委托给两个模型,更喜欢使用一个模型而不是另一个模型。我使用了:prefix选项:

from individual.rb

来自individual.rb

delegate :referral_key, :email, :username, :first_name, :last_name, :gender, :approves_email, :approves_timeline, to: :user, allow_nil: true, prefix: true                                
delegate :email, :first_name, :last_name, to: :visitor, allow_nil: true, prefix: true

def first_name
  user.present? ? user_first_name : visitor_first_name
end

相关文章