0
所以提交表單我Testimony
模型後,我得到了下面的活動在我的rails控制檯:Rails 4.0.4:如何顯示創建記錄是否成功?
Processing by TestimoniesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y7n/+rlDoH3ys68HMOh6T6WFpAelRT18WUPstCz41vE=", "testimony"=>{"first_name"=>"bob ", "last_name"=>"balaban", "email"=>"", "contact_number"=>"", "country"=>"", "question1"=>"", "question2"=>"", "question3"=>"", "question4"=>"", "question5"=>"", "signature"=>"", "waiver"=>"0"}, "commit"=>"Save Testimony"}
(0.1ms) begin transaction
Testimony Exists (0.2ms) SELECT 1 AS one FROM "testimonies" WHERE ("testimonies"."last_name" = 'balaban' AND "testimonies"."first_name" = 'bob ' AND "testimonies"."email" = '') LIMIT 1
(0.1ms) rollback
這裏是TestimoniesController
class TestimoniesController < ApplicationController
def new
end
def index
end
def show
@testimony = Testimony.find(params[:id])
end
def create
@testimony = Testimony.new(post_params)
@testimony.save
redirect_to @testimony
end
private
def post_params
params.require(:testimony).permit(:first_name, :email, :last_name, :contact_number, :country, :question1, :question2, :question3, :question4, :question5, :signature, :waiver)
end
end
這裏是我的Testimony.rb
class Testimony < ActiveRecord::Base
validates_presence_of :first_name, :last_name,:email, :contact_number, :country, :question1, :question2, :question3, :question4, :question5, :signature, :waiver
validates_uniqueness_of :last_name, :scope => [:first_name, :email]
end
型號文件
我想顯示一條消息,如: 已記錄已存在TS
或者 所有字段需要填寫
我意識到這是很可悲的,但我認爲這是Rails的魔法的一部分斷言所有模型的在該領域的獨特性和存在表單級別,然後再執行@ modelname.save。我顯然不是很明白。謝謝你的幫助。
謝謝,但在第一個解決方案中,我該如何區分參數是否缺失以及記錄是否存在?有一種我可以模式匹配的錯誤值嗎? – Thalatta
檢查https://github.com/rails/strong_parameters以及該記錄是否存在?如果'@ model.save!'通過,那麼每個都是好的,這是一個新的記錄。否則會出現錯誤並引發異常,這個異常可能是您引發的事情(您創建的自定義異常)或驗證或從模型回調引發的異常... –
啊。所以就像你在編寫'ActionController :: ParameterMissing'時你正在匹配那個錯誤,不是嗎?你怎麼能捕捉到像'ActionController :: DuplicateRecord'這樣的真實版本?我很難在文檔中找到它。 – Thalatta