Reputation: 3090
I'm trying to add a coupon to my checkout page, using an AJAX request that validates the coupon and updates the price accordingly. However, on loading the checkout view I get the error message:
First argument in form cannot contain nil or be empty
referring to the line <%= form_for @actioncode, method: :post ...
in the form where the coupon is entered. I've tried to follow the steps here. How should I adjust my code?
The set up: @actioncode refers to a model where the admin stores actioncodes. Coupon_code is not included in any model but refers to the value that a user enters in the form. Coupon_code should be checked against the Actioncode model (specifically the 'actioncode' column) if the value exists (validation) and if so update the price based on the value in the Actioncode model in the colum 'discount'.
The checkout view contains the following form:
<%= 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 %>
Routes:
post 'check_actioncode' => 'actioncodes#check_actioncode'
In the actioncodes controller I have:
def check_actioncode
@actioncode = Actioncode.find(params[:coupon_code])
respond_to do |format|
if [email protected]?
format.js {}
else
flash.now[:success] = "Action code not found or expired"
end
end
end
The organizations controller renders the checkout 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
Update: If I add @actioncode = Actioncode.new
to the controller that loads the view, I get another error message undefined method 'coupon_code'
referring to the 2nd line of the form. coupon_code
is indeed a variable nowhere defined but it should simply be a temporary value that the user has entered and that is checked against the actioncode in the model for validation. How should I do this?
Upvotes: 1
Views: 292
Reputation: 43308
Change your form to:
<%= form_for @actioncode, method: :post, url: {action: "check_actioncode", :controller => 'actioncodes'}, remote: true do |f| %>
<%= f.text_field :actioncode, :placeholder => "Enter your coupon" %>
Change your controller to:
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
Upvotes: 1