[英]Keep changes on reload if validation fails
我正在使用rails中的驗證,例如:
validates_presence_of :some_field
我注意到如果驗證失敗,所有更改都會被數據庫中的現有值覆蓋。 這是有道理的,因為頁面基本上被重新加載(因為我從我的開發日志中收集),然而這增加了用戶錯誤/挫折的風險,因為在一個字段中的單個錯誤將需要不幸的家伙重新進入他對所有領域的改變。
我的問題:如果驗證失敗,我怎樣才能重新加載剛剛提交的數據? 這樣,用戶可以糾正錯誤,而無需重新輸入其他修訂版本。
謝謝你的建議。
編輯:我的更新方法,如要求,如下:
def update
@incorporation = Incorporation.find(params[:id])
@company = @incorporation.company
begin
@company.name="#{params[:company][:names_attributes].values.first["name_string"]} #{params[:company][:names_attributes].values.first["suffix"]}"
rescue NoMethodError
@company.name="Company #{@company.id} (Untitled)"
end
if @company.update(company_params)
redirect_to incorporations_index_path
else
redirect_to edit_incorporation_path(@incorporation)
end
end
關於我的控制器的完整信息:上述update
來自我的incorporations_controller
即使我正在更新我的Company
模型。 Company has_one :incorporation
。 我這樣做是因為,在我的應用程序的更大范圍內,它使我的協會更清潔。
將控制器更新為此
def update
@incorporation = Incorporation.find(params[:id])
@company = @incorporation.company
begin
@company.name="#{params[:company][:names_attributes].values.first["name_string"]} #{params[:company][:names_attributes].values.first["suffix"]}"
rescue NoMethodError
@company.name="Company #{@company.id} (Untitled)"
end
respond_to do |format|
if @company.update(company_params)
format.html { redirect_to({:action => "index"})}
else
format.html{render :edit}
format.json { render json: @incorporation.errors, status: :unprocessable_entity }
end
end
end
要添加正確的答案,您可以完全清理代碼:
def update
@incorporation = Incorporation.find params[:id]
respond_to do |format|
if @incorporation.update company_params
format.html { redirect_to({:action => "index"})}
else
format.html { render :edit }
format.json { render json: @incorporation.errors, status: :unprocessable_entity }
end
end
end
如果您使用accepts_nested_attributes_for
,你絕對不應該砍在前端的相關聯的對象。
你應該查找fat model, skinny controller
(讓模型完成工作):
#app/models/company.rb
class Company < ActiveRecord::Base
before_update :set_name
attr_accessor :name_string, :name_suffix
private
def set_name
if name_string && name_suffix
self[:name] = "#{name_string} #{name_suffix}"
else
self[:name] = "Company #{id} (Untitled)"
end
end
end
這將允許您填充`公司的name
。 直接編輯嵌套/關聯對象是一個反模式 ; 一個黑客,后來會回來困擾你。
答案的關鍵是: render :edit
渲染編輯視圖意味着維護當前的@company
/ @incorporation
數據。
重定向將調用controller
的新實例,覆蓋@incorporation
,因此您在前端看到的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.