如果ActiveRecord对象中的属性为零,我该如何设置它?

时间:2010-09-04 10:43:30

标签: 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

我喜欢在控制台中调用这些东西,比如

Mutant.create(:style => "rampage") # expected is Mutant.first.style == "rampage"
Mutant.create # expected is Mutant.last.style == "hardcore but this doesn't work

2 个答案:

答案 0 :(得分:1)

  1. 首先,请看这个问题:What is the best way to set default values in activerecord
  2. style = "hardcore" unless style将实例化一个名为“style”的新变量,而不是设置现有属性。将其更改为引用 self ,如下所示:self.style = "hardcore" unless style
  3. 最后将作业写成self.style,如下所示:self.style ||= "hardcore"这是您当前所写内容的快捷方式。
  4. 我可能会这样写:

     class Mutant < ActiveRecord::Base   
       attr_accessible :style
       after_initialize :setup_values
    
       private
       def setup_values 
         self.style ||= "hardcore"
       end   
     end
    

答案 1 :(得分:0)

刚刚在api中找到它

def setup_values 
  write_attribute :style, "hardcore" if style.blank?  
end
tadaa,它有效:)