我正在尝试使用 AJAX 请求将优惠券添加到我的结账页面,该请求验证优惠券并相应更新价格。但是,在加载结帐 View 时,我收到错误消息:
First argument in form cannot contain nil or be empty
引用行<%= form_for @actioncode, method: :post ...
以输入优惠券的形式。我尝试按照步骤 here 进行操作。我应该如何调整我的代码?
设置:@actioncode 指的是管理员存储操作代码的模型。 Coupon_code 不包含在任何模型中,但指用户在表单中输入的值。应根据 Actioncode 模型(特别是“actioncode”列)检查 Coupon_code 值是否存在(验证),如果存在,则根据“discount”列中 Actioncode 模型中的值更新价格。
结账 View 包含以下表单:
<%= form_for @actioncode, method: :post, url: {action: "check_actioncode"}, remote: true do |f| %>
<%= f.text_field :coupon_code, :placeholder => "Enter your coupon" %>
<%= f.submit "Submit Coupon Code" %>
<% end %>
路线:
post 'check_actioncode' => 'actioncodes#check_actioncode'
在操作代码 Controller 中,我有:
def check_actioncode
@actioncode = Actioncode.find(params[:coupon_code])
respond_to do |format|
if !@actioncode.nil?
format.js {}
else
flash.now[:success] = "Action code not found or expired"
end
end
end
组织 Controller 呈现结账 View :
def checkout
@organization = Organization.new(organizationnew_params)
if @organization.save
@organization.members.each do |single_member|
single_member.send_activation_email
end
@actioncode = Actioncode.new
@amount = 100.00
@currency = "EUR"
@description = @organization.id
@transaction_description = "My description"
@transaction_type = "S"
@hash = hash(@description, @amount, @currency, @transaction_type)
render 'checkout' # This renders the checkout view.
else
render 'new_premium'
end
end
更新:如果我添加 @actioncode = Actioncode.new
对于加载 View 的 Controller ,我收到另一条错误消息 undefined method 'coupon_code'
引用表格的第二行。 coupon_code
确实是一个没有定义的变量,但它应该只是用户输入的临时值,并根据模型中的操作代码进行检查以进行验证。我该怎么做?
最佳答案
将您的表单更改为:
<%= form_for @actioncode, method: :post, url: {action: "check_actioncode", :controller => 'actioncodes'}, remote: true do |f| %>
<%= f.text_field :actioncode, :placeholder => "Enter your coupon" %>
将 Controller 更改为:
def check_actioncode
@actioncode = Actioncode.where(:actioncode => params[:actioncode][:actioncode]).first
respond_to do |format|
unless @actioncode.blank?
format.js {}
else
flash.now[:success] = "Action code not found or expired"
end
end
end
关于javascript - 如何自动验证优惠券并调整价格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140222/