Ruby on rails 如何仅在ActiveRecord对象为nil时设置其属性?

Ruby on rails 如何仅在ActiveRecord对象为nil时设置其属性?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,对不起,我觉得我今天有点笨 class Mutant < ActiveRecord::Base attr_accessible :style before_create :setup_values private def setup_values style = "hardcore" unless style end end 刚刚在api中找到它 def setup_values write_attribute :style, "hardcor

对不起,我觉得我今天有点笨

class Mutant < ActiveRecord::Base
  attr_accessible :style

  before_create :setup_values


  private

  def setup_values 
    style = "hardcore" unless style
  end
end

刚刚在api中找到它

def setup_values 
  write_attribute :style, "hardcore" if style.blank?  
end
tadaa和它的作品:)

  • 首先,看这个问题:
  • style=“hardcore”除非style将实例化名为“style”的新变量,而不是设置现有属性。将其更改为引用self-like so:
    self.style=“hardcore”除非style
  • 最后,像这样将作业写到self.style:
    self.style | |=“hardcore”
    ,这是您当前所写内容的快捷方式
  • 我可能会这样写:

     class Mutant < ActiveRecord::Base   
       attr_accessible :style
       after_initialize :setup_values
    
       private
       def setup_values 
         self.style ||= "hardcore"
       end   
     end
    
    类变种
    您想使用self.style=。。。只执行style=X,Ruby将其解释为局部变量,而不是对#style=的方法调用。
     class Mutant < ActiveRecord::Base   
       attr_accessible :style
       after_initialize :setup_values
    
       private
       def setup_values 
         self.style ||= "hardcore"
       end   
     end