我有用户可以订阅最新优惠券的表格。当我在多个选项卡中打开同一个商店链接并订阅时,我会为单个商店获得多个订阅,导致数据重复并多次发送相同的邮件。所以在模型上添加了验证。所以问题是我如何让错误显示在视图中。当用户已经订阅了商店时。由于创建正在发出 ajax 请求。我已经粘贴了下面的代码。任何帮助将不胜感激谢谢
_index.html.haml(视图)
=form_for([@merchant,@coupon_subscription],:remote => true,:html => { :class => "store_subscribe" } ) do |f|
%h3 subscribe for #{@merchant.merchant_name} coupons
-if !logged_in?
=f.text_field :user ,:class => "input_text email"
=f.submit "Subscribe",:disable_with => "Subscribing...",:class => "store_subscribe subscribe_button"
订阅控制器
def create #creates subscription
return if !logged_in?
return if current_user.subscription_limit?
@merchant=Merchant.find_by_permalink(params[:merchant_id])
@coupon_subcription=CouponSubscription.new(:merchant_id => @merchant.id,:user => current_user)
@coupon_subcription.coupon_subscribe
respond_to do |format|
if @coupon_subcription.save!
format.html { redirect_to(:back, :notice => 'Success.') }
format.js
else
format.html { redirect_to(:back, :notice => @coupon_subcription.errors.full_messages || "Oops something went wrong")}
format.js
end
end
UserMailer.delay.coupon_subscription(current_user,@coupon_subcription)
结尾
模型
validate :validate_subscription ,:on => :create
private
def validate_subscription
@coupon_subscribed=CouponSubscription.find_by_user_id_and_merchant_id_and_active(self.user_id,self.merchant_id,true)
if @coupon_subscribed
self.errors.add(:base , 'You have already subscribed.')
end
结尾
创建.js
<% if !logged_in? %>
$(".store_subscribe").remove()
$(".subscription_feedback").show().append("Login!")
<% else %>
$(".store_subscribe").remove()
$(".store_subscribe").show().append("<h3>Thanks for subscription .We have send you a mail </h3>")
<% end %>