2011-11-25 48 views
0

這是一個由兩部分組成的問題。第1部分詢問我的結構是否正確(它正在工作,我只想知道這是否是Rails的方式)。第2問如何真正做到問題在這篇文章的標題,在這裏我們去:運行gsub後數據庫中的Ruby on Rails批量更新記錄

我有以下的結構,我的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上的更新操作(因爲Model不知道更新方法)?

Socjopata:我根據您的建議ammended我的模型正是如此:

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! 

回答

0
  1. 是的,邏輯應該放在模型中。
  2. 那麼是什麼讓你無法通過更新你的@dvds來增強你的remove_parens?像

    _instance_of_a_dvd_model.update_attribute(:標題,_gsubbed_title)

而且,你並不需要在模型中 「@」 你的局部變量。另外你爲什麼在視圖中設置fullText變量?你在什麼地方使用它?如果是,那麼你知道你的觀點應該是相當邏輯自由的?

+0

這些都是很好的問題,讓我試着回答它們:1.什麼阻止我是無知:)我不知道該怎麼做。不知道這是什麼意思'_instance_of_a_dvd_model.update_attribute(:title,_gsubbed_title)'(新的Rails,抱歉)。我想我已經掌握了它的要點,讓我試試看。沒有@,非常感謝。 – kakubei

+0

3.在視圖中的fullText,使格式看起來不錯。我會怎麼做?我會把它放入控制器嗎?如果是這樣的話?由於控制器不知道dvd.title的含義。 – kakubei

0

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

此外,呼籲的gsub!回報strip!可能是危險的。如果gsub!不作任何替換,則它將返回零,並且您將嘗試在nil上調用strip!。在這種情況下,我認爲你想用gsub(不帶!)代替。