Tips for automatically verifying coupons and adjusting prices

My current task involves implementing a coupon feature on the checkout page using an AJAX request to validate the coupon and adjust the price accordingly. However, when the checkout view is loaded, I encounter an error message:

The first argument in the form cannot be nil or empty

This error points to the line

<%= form_for @actioncode, method: :post ...
in the form where the coupon is supposed to be entered. I have attempted to follow the guidelines provided here. How should I modify my code to resolve this issue?

Situation: The @actioncode variable represents a model that contains action codes stored by the admin. The coupon_code value is not associated with any model but refers to the user input in the form. This coupon_code needs to be validated against the 'actioncode' column in the Actioncode model and if valid, update the price based on the 'discount' value in the Actioncode model.

The checkout view includes 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, the check_actioncode method is defined as follows:

def check_actioncode
  @actioncode = Actioncode.find(params[:coupon_code])
  respond_to do |format|
    if <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b899f8d9dbccd1d7d6dbd7dcdd96d6d1d4">[email protected]</a>?
      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: When I include @actioncode = Actioncode.new in the controller that loads the view, I encounter another error stating undefined method 'coupon_code', which pertains to the second line of the form. Although 'coupon_code' is not explicitly defined anywhere, it should simply represent the temporary user input that is validated against the actioncode in the model. What steps should I take to address this issue?

Answer №1

Revise your form as follows:

<%= form_for @actioncode, method: :post, url: {action: "check_actioncode", :controller => 'actioncodes'}, remote: true do |f| %>
  <%= f.text_field :actioncode, :placeholder => "Please enter your coupon code" %>

Update your controller like this:

def check_actioncode
  @actioncode = Actioncode.where(:actioncode => params[:actioncode][:actioncode]).first

  respond_to do |format|
    unless @actioncode.blank?
      format.js {}
    else
      flash.now[:success] = "Sorry, the action code could not be found or has expired"
    end
  end
end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jquery ready function key event

When using AJAX to load elements on my page, I have a requirement where pressing Enter should move the focus to the next input, textarea, or select element. Some inputs also have a number formatting function applied, but the current solution runs multipl ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

I require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods. //CODE class Form{ constructor(){ var self = this; } assemble(){ log(self); ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

Utilizing the document.createDocumentFragment() method along with innerHTML for manipulating a Document Object Model (

I am currently in the process of creating a document fragment using the code below: let fullHTMLDocument = '<!doctype html> <html><head></head><body><h1>hello world</h1></body></html>'; let f ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Why should <template> be used in Vuetify?

Exploring the possibilities of Vuetify 2.0 in my current project has led me to dive into the v-stepper component, designed for displaying progress through numbered steps. In the example provided in the playground, I noticed the use of the <template> ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

How to bypass CORS restrictions in XMLHttpRequest by manipulating HTTP headers?

Currently experimenting with the (deprecated) Twitter API 1.0 For instance, I am interested in retrieving data from the API utilizing AJAX browser requests on cross-origin web pages. This could be a new tab, a local HTML file, or any established website. ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Form validation displaying only the initial error message

When validating a form, I am encountering an issue where only the first error message can be displayed: ContactUs.prototype.desktopErrors = function(){ var THIS = this; THIS.$el.find('#submit').on('click', function(){ ...