這是一個由兩部分組成的問題。第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)。
- 這是在Rails中做事的正確方法嗎?將大部分代碼放在模型中,然後讓控制器簡單地調用該函數?
- 我意識到這只是打印出更改,而不是將它們寫回數據庫。我想把它們寫回數據庫,我將如何實現這一目標?也許通過調用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!
這些都是很好的問題,讓我試着回答它們:1.什麼阻止我是無知:)我不知道該怎麼做。不知道這是什麼意思'_instance_of_a_dvd_model.update_attribute(:title,_gsubbed_title)'(新的Rails,抱歉)。我想我已經掌握了它的要點,讓我試試看。沒有@,非常感謝。 – kakubei
3.在視圖中的fullText,使格式看起來不錯。我會怎麼做?我會把它放入控制器嗎?如果是這樣的話?由於控制器不知道dvd.title的含義。 – kakubei