【问题标题】:how to replace null by value of an attribute in rails console如何在rails控制台中用属性值替换null
【发布时间】:2012-07-23 08:20:46
【问题描述】:

我正在编写一个模型为 Allissue 的 redmine 插件。我添加了两个属性project_namecreate_date。首先,我添加了project_name 列并为它们分配了一些值。其次,我又添加了一列created_date,其值变为空,如图所示。

我想用整数值替换 null。这是一个非常基本的问题,但我不知道,因为我是新手。你能建议我添加值的语法吗?谢谢

【问题讨论】:

    标签: ruby-on-rails-3 redmine-plugins rails-console


    【解决方案1】:

    要自动发生这种情况,请在您的模型中添加如下内容:

    class Allissue
      ...
      before_save do |a|
        a.create_date = Time.now # or whatever you want it to be
      end
      ...
    end
    

    或手动,您会这样做(对于所有多个对象):

    Allissue.all.each{|a| a.create_date = Time.now; a.save}
    

    或(对于单个对象):

    a = Allissue.find(1)
    a.create_date = Time.now
    a.save
    

    我希望这会有所帮助。

    【讨论】:

    • 谢谢...但是 create_date 不是魔术列,所以我无法将它与 Time.now 联系起来。这取决于项目的观点。
    • 你能回答我的另一个[问题]:(stackoverflow.com/questions/11607405/…)
    猜你喜欢
    • 2017-10-23
    • 2023-03-27
    • 2016-03-30
    • 2017-04-17
    • 1970-01-01
    • 2019-12-10
    • 2011-05-11
    • 1970-01-01
    • 2022-08-21
    相关资源
    最近更新 更多