繁体   English   中英

运行gsub后,Ruby on Rails批量更新数据库中的记录

[英]Ruby on Rails batch updating records in database after running gsub

这是一个分为两部分的问题。 第1部分询问我的结构是否正确(它正在运行,我只想知道这是否是Rails的处理方式)。 第2部分询问如何实际完成本文标题中的问题,我们开始:

我的Dvd模型具有以下结构:

def self.remove_parens 
    # we will remove the beginning parentheses from the entries sent to us by the parens method
    @dvds = self.parens # get the entries we need to edit
    @dvds.each do |dvd|
        @newDvds = dvd.title.gsub!(/^\([0-9]*\)/, '')
    end
end

在DvdsController文件中:

  def fixer
    @newDvds = Dvd.remove_parens
  end

在修复程序视图文件中:

<% 
  @newDvds.each do |dvd| 
    fullText = "#{dvd.title}"
%>

这很好用,我可以看到gsub的结果正在起作用,并且从标题中删除了(245)之类的条目。

  1. 这是在Rails中做事的正确方法吗? 将大多数代码放入模型中,然后让控制器简单地调用该函数?
  2. 我意识到这只是打印出更改,而不是将更改写回到数据库。 我想将它们写回到数据库中,我该怎么做? 也许通过在Controller中的@newDvds上调用更新操作(因为模型不知道更新方法)?

Socjopata:因此,我根据您的建议对模型进行了修正:

dvds = self.parens # get the entries we need to edit
dvds.each do |dvd|
    fixedTitle = dvd.title.gsub!(/^\([0-9]*\)/, '') # this prints it out but doesn't change the entries in the table
    dvd.update_attribute(:title, fixedTitle) # this is supposed to update the attribute in the table
end

但是它不会更新数据,表中的数据仍然相同。

我最终要做的是,这似乎可以解决问题:

Dvd.update(dvd.dogTag, { :title => fixedTitle } )

现在,我需要修剪该标题,以便计算出如下内容:

fixedTitle = dvd.title.gsub!(/^\([0-9]*\)/, '').strip!

fixedTitle = dvd.title.gsub!(/^\\([0-9]*\\)/, '').strip! 有几个微妙的问题,第一个是为什么数据库没有更新。

gsub! 修改字符串,并绕过(从3.2.7版本开始)ActiveRecord知道实例是否已更改的方式。 它认为DVD实例仍然没有改变,因此跳过了更新数据库的操作。

相比

dvd.title.gsub!(/^\\([0-9]*\\)/, '')
dvd.changed? # => always false if no other changes were made

dvd.title = dvd.title.gsub(/^\\([0-9]*\\)/, '')
dvd.changed? # => true if title was changed

还有,叫strip! gsub!的回报上gsub! 可能很危险。 如果gsub! 不进行任何替换,则它将返回nil,您将尝试调用strip! 零。 在这种情况下,我认为您想使用gsub (不带!)。

  1. 是的,逻辑应该放在模型中。
  2. 那么是什么阻止你提高你的remove_parens与更新@dvds? 喜欢

    _instance_of_a_dvd_model.update_attribute(:title,_gsubbed_title)

另外,您无需在模型中“ @”局部变量。 另外,为什么要在视图中设置fullText变量? 你在某处使用它吗? 如果是,那么您知道您的视图应该没有逻辑吗?

暂无
暂无

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

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