【问题标题】:ruby first_or_create method not updating the model & databaseruby first_or_create 方法不更新模型和数据库
【发布时间】:2013-10-07 14:22:17
【问题描述】:

您好,我有一个包含 Channel 模型的 rails 应用程序。其属性如下:

   # Table name: channels
   #
   #  id             :integer          not null, primary key
   #  created_at     :datetime
   #  updated_at     :datetime
   #  channel_name   :string(255)
   #  classification :string(255)      default("0")
   #  ownership      :string(255)      default("0")

我的应用程序中的一个 rake 任务读取了一个 csv 文件并在数据库中填充了信息。这是创建模型的代码快照

    ...previous code........

    channelName = nil
    classif = nil
    owner = nil
    channelName = row[0].force_encoding('UTF-8')
    classif = row[1].force_encoding('UTF-8')
    owner = row[2].force_encoding('UTF-8') 

if (channelName.nil?)
       puts "Channel name for row #{i} was nil"
       next 
    else                                    
       puts "Creating channel hash with information:"
   puts "channel_name= #{channelName}"
   puts "classification=#{classif}"
   puts "ownership= #{owner}"

   ch = Channel.where(:channel_name =>"#{channelName}").first_or_create do |c|
   c.ownership = "#{owner}"
   c.classification = "#{classif}"

由于任务能够读取 csv 文件并填充数据库,因此“first_or_create”方法的“create”部分有效。但是,当我更改 csv 文件中的某些内容并重做 rake 任务时,它应该使用更改的内容更新数据库。它不这样做。我想知道这与我的方法的语法有关吗?方块部分错了吗?

【问题讨论】:

  • @dax 请停止编辑提问者的帖子,尤其是如果您只是删除“感谢您的帮助”部分...
  • 嗨@MrYoshiji,我要离开this,有人在回答我自己的问题时引用了该消息。

标签: ruby-on-rails csv model rake updatemodel


【解决方案1】:

first_or_create 的文档并没有说如果记录已经存在,它会更新它。它

  1. 如果记录不存在,则创建该记录。
  2. 如果记录已经存在则返回

您必须在获得记录后对其进行更新。

ch = Channel.where(:channel_name =>"#{channelName}").first_or_create do |c|
   c.ownership = "#{owner}"
   c.classification = "#{classif}"
end

ch.update_attribute(:attr, value)

【讨论】:

  • update_attribute: (from doc): "Updates a single attribute and saves the record without going through the normal validation procedure" => 改用update_attributes(复数),它将通过验证过程
猜你喜欢
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
相关资源
最近更新 更多