简体   繁体   English

仅当ActiveRecord对象为nil时,才如何设置属性?

[英]How do I set attributes in an ActiveRecord Object only if it is nil?

Sorry, I think I am a bit stupid today 对不起,我今天有点傻

class Mutant < ActiveRecord::Base
  attr_accessible :style

  before_create :setup_values


  private

  def setup_values 
    style = "hardcore" unless style
  end
end

I like to call this stuff in the console like 我喜欢在控制台中称呼这些东西

Mutant.create(:style => "rampage") # expected is Mutant.first.style == "rampage"
Mutant.create # expected is Mutant.last.style == "hardcore but this doesn't work
  1. First off, see this question: What is the best way to set default values in activerecord 首先,请参见以下问题: 在activerecord中设置默认值的最佳方法是什么
  2. style = "hardcore" unless style will instantiate a new variable named 'style' rather than setting the existing property. style = "hardcore" unless style将实例化名为'style'的新变量,而不是设置现有属性。 Change it to reference self like so: self.style = "hardcore" unless style 像这样将其更改为引用selfself.style = "hardcore" unless style
  3. Lastly write the assignment to self.style like so: self.style ||= "hardcore" which is a shortcut for what you've currently written. 最后,如下所示将分配写到self.style ||= "hardcore" ,这是您当前编写的快捷方式。

I'd probably write it like this: 我可能会这样写:

 class Mutant < ActiveRecord::Base   
   attr_accessible :style
   after_initialize :setup_values

   private
   def setup_values 
     self.style ||= "hardcore"
   end   
 end

just found it in the api 刚刚在api中找到了它

def setup_values 
  write_attribute :style, "hardcore" if style.blank?  
end

tadaa and it works :) 塔达阿,它的工作原理:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在保存之前,如何在ActiveRecord对象中设置属性? - How do I set attributes in an ActiveRecord Object before I save it? 如何仅允许更新Rails ActiveRecord对象的nil属性? - How can I only allow updating of nil attributes for a Rails ActiveRecord object? 如何在ActiveRecord回调中设置属性? - How do I set attributes in an ActiveRecord Callback? 使用ActiveRecord,如何编写仅包含值不为空/无的对象的where语句? - With ActiveRecord, how do I write a where statement that only includes objects whose values aren't blank/nil? 将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么? - What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil? Rails:ActiveRecord和send;如何只知道类名来设置activerecord实例的关系? - Rails: ActiveRecord and send; how do I set an activerecord instance's relation with only knowing the class names? 计算ActiveRecord nil属性 - Computing ActiveRecord nil attributes 如何检查类或json对象中的所有属性/值均为nil - how do i check that all attributes/values in a class or json object are nil 将ActiveRecord对象包装为PORO。 如何获得所有属性? - Wrapping an ActiveRecord object as a PORO. How do get all the attributes? Rails activerecord .select导致对象具有所有nil属性 - Rails activerecord .select causing object to have all nil attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM