我想检查数据库中是否存在数据..如果不是我应该保存数据..我用过吗?控制器中的方法如下..
def party_order_create
@party_order = PartyOrder.new(party_order_params)
if not PartyOrder.exists?(@party_order)
then @party_order.save
flash[:notice] = "Party Saved Successfully!!!"
redirect_to :action => "party_order_index"
else
flash.now[:notice] = "Party not Saved"
render "party_order_new"
end
end
它不起作用..请帮我纠正..
答案 0 :(得分:0)
尝试使用
if @party_order.present?
而不是:
if PartyOrder.exists?(@party_order)
所以它可以改写为:
def party_order_create
@party_order=PartyOrder.new(party_order_params)
@party_order.save
if @party_order.present?
flash[:notice] = "Party Saved Successfully!!!"
redirect_to :action => "party_order_index"
else
flash.now[:notice] = "Party not Saved"
render "party_order_new"
end
end
答案 1 :(得分:-2)
@party_order=PartyOrder.find_or_create_by(party_order_params)
if @party_order.present?
// code
else
// code
end
//或试试这个
@party_order=PartyOrder.where(party_order_params)
if @party_order.present?
flash.now[:notice] = "Party not Saved"
render "party_order_new"
else
@party_order=PartyOrder.new(party_order_params)
if @party_order.save
flash[:notice] = "Party Saved Successfully!!!"
redirect_to :action => "party_order_index"
end
end