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

Is there a way to alter the timestamp on comments in a React Native app, similar to Instagram's functionality, using dayjs?

I am currently working on a project using react native in combination with dayjs library. My goal is to compare the timestamp of when a comment was written with the current time, and then display this compared time using console.log() with the help of day ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

Is there a method to prevent the repetition of this loop?

I have a question regarding my React app development. I am currently using useEffect to loop through six items every time, even when only one item has changed. How can I optimize this so that only the variable that was changed in the reducer function is ...

Unable to trigger onClick event in React class-based component

I came across the following code for a class-based component: class PostLike extends Component { constructor(props) { super(props); this.state = { likes: null, like_id: null } this.likeSubmit = t ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Load full html content, including doctype, into a jQuery container | Block scripts from running in iFrames

I am attempting to fetch an entire HTML file using AJAX and then manipulate the DOM with jQuery. This means that the retrieved HTML document includes a doctype and other top-level elements. The process of retrieving the HTML is straightforward: $.get(&ap ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

Issues with displaying search form div using jQuery AJAX

Currently, I am in the process of developing a search form that includes a dropdown menu. The functionality involves selecting an item from the dropdown menu triggering an AJAX call to another PHP file. This call returns tags which resize both the dropdown ...

What is the method to retrieve a checkbox value within a datatable when employing pagination?

I recently came across an issue with my datatable where I had implemented a checkbox in the first column of each row. However, when I attempted to check the checkbox using an AJAX call, it only worked for the first page and not for any subsequent pages. H ...

Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form. For instance, when the user selects "True", I want the value stored as true in boolean format ...

Challenges when Implementing JQuery Tab Components

I am currently working on adding new tabs to my existing tab system created with jQuery. My approach involves assigning a class "extend" to the anchors that will create the new tabs and removing their default functionality. I then load the content into t ...

How to send parameters to the jquery .css() method

I'm attempting to create hyperlinks that can dynamically set inline styles for different elements on a webpage. I have managed to save the element and attribute settings in hidden span elements and retrieve them to display in an alert dialog. However, ...

Ensure that you provide two arguments when calling the $.ajax success function

I'm facing a little issue. I'm trying to send two variables from PHP to the $.ajax success function Here's my JS code: $.ajax({ type:"POST", url:path, data: "value="+info, success:function(data, data1) { if(dat ...

Inconsistent 404 Error when Making Socket.io Ajax Requests

My Node server is responsible for managing user sessions, chatrooms, messaging, web scraping, and other tasks. Sometimes, when attempting to send messages from the website to the Node server, I encounter a 404 error in the response. This issue occurs rare ...

Why doesn't the 'Range' input type slide on React.js documentation, but it does on CodePen?

Can someone help me figure out why my range slider is not working in my React app? I copied the code from Codepen where it works fine, but in my app, it's not functioning properly. The slider doesn't slide when dragged and clicking on it doesn&a ...

Implementing Entity addition to a Data Source post initialization in TypeORM

The original entity is defined as shown below: import { Entity, PrimaryGeneratedColumn} from "typeorm" @Entity() export class Product { @PrimaryGeneratedColumn() id: number The DataSource is initialized with the following code: import ...

Implement a callback function in React using hooks after changing the state

Back in the days of React before hooks, setting state and calling a function after it had been set was achieved using the following syntax: this.setState({}, () => {//Callback}) Now, with hooks, what is the equivalent way to achieve this? I attempted ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

End the child process.execution after a specific amount of time

I have been searching for information on child process waiting time or response waiting time, but I haven't found anything useful. I'm in need of something like that, so I hope someone can assist me. When I look at the code below, I am printing ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...