简体   繁体   English

将具有相同值的Rails模型属性设置更改吗? 返回真吗?

[英]Will setting Rails model attributes with the same value make changed? return true?

I'm looking to make my db:seed task a little more dynamic by allowing certain entries in my application to be created or updated (or nothing at all) based on the values of in db/seeds.rb and the current state of the backend database. 我希望通过允许基于db/seeds.rb的值和应用程序的当前状态来创建或更新应用程序中的某些条目(或根本不执行任何操作),使db:seed任务更具动态性。后端数据库。 I'm also looking to simplify the functions that carry this logic out. 我还希望简化实现此逻辑的功能。

I'd like to avoid this: 我想避免这种情况:

def create_or_update_config(key, value)

  ...

  if config_entry.value != value
    config_entry.value
  end

  if config_entry.changed?
    config_entry.save
  end

  ...

end

And instead have something simplistic: 而是简单一些:

def create_or_update_config(key, value)

  ...

  config_entry.value = value

  if config_entry.changed?
    config_entry.save
  end

  ...

end

Is ActiveRecord smart enough to know if attribute values have changed even if they've been set (with the same value)? ActiveRecord是否足够聪明,即使设置了属性值(具有相同的值),也知道属性值是否已更改?

Yes. 是。 ActiveRecord's changed? ActiveRecord changed? method will return true only if there were mutations since the last save. 仅当自上次保存以来存在突变时,该方法才返回true。 From an example using my own app's console (Rails 5.1.6): 使用我自己的应用程序控制台的示例(Rails 5.1.6):

irb(main):013:0> config.value
=> "http://localhost:3100"
irb(main):014:0> config.value = "http://localhost:3100"
=> "http://localhost:3100"
irb(main):015:0> config.changed?
=> false
irb(main):016:0> config.value = "anything else"
=> "anything else"
irb(main):017:0> config.changed?
=> true

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM