Adding unique parameters to a rails form

As a newcomer to web development, I am facing the following challenge:

I have three models in my application:

products

class Product < ApplicationRecord
  has_and_belongs_to_many :steps
end

steps

class Step < ApplicationRecord
  has_and_belongs_to_many :products
end

products_steps

class ProductsStep < ApplicationRecord
  belongs_to :product
  belongs_to :step

The issue at hand involves a form with multiple buttons that need to be selected to determine the steps associated with a product.

https://i.sstatic.net/DqcoW.png

I am struggling to figure out how to pass the selected steps as parameters to my product controller. My attempts involve using JavaScript to handle this information, but I am unsure of how to proceed with sending it.

function add_h(){
    #detecting if the button is selected or not
    btn_on = document.getElementById("hyd_on");
    btn_off = document.getElementById("hyd_off");
    if(btn_on != null){
      #adding the step related to the selected button
      <% @steps << Step.where(:id => 1) %>
      <% puts "#{@steps.count}" %>
      btn_on.style.background='#686761';
      btn_on.style.border='#686761';
      btn_on.setAttribute("id", "hyd_off");
    }else if (btn_off != null){
      #removing the step
      <% if @steps.count < 0 then @steps.where(:id => 1).first.destroy end %>
      <% puts "#{@steps.count}" %>
      btn_off.style.background='#d463c5';
      btn_off.style.border='#d463c5';
      btn_off.setAttribute("id", "hyd_on");
    }
}

Within the controller, my logic is as follows:

def new
    @product = Product.new()
    @steps = Array.new()
    if Product.all.any?
      @product.id = Product.last.id + 1
    else
      @product.id = 1
    end
end

def create
    @product = Product.new(product_params)
end

I have a feeling that I might be approaching this problem incorrectly. While JavaScript seems like a viable option, I am open to exploring other solutions for handling this scenario.

Answer №1

Upon initial observation, it is clear that in a has_and_belong_to_many relationship, a joint table like model1s_model2s is required in the database (note the ending 's' for the plural of the model name). It is important to note that there is no need for a specific model dedicated to the joint table.

Furthermore, the necessity of the mentioned code snippet is uncertain.

products_steps

class ProductsStep < ApplicationRecord   
belongs_to :product  
belongs_to :step 
end

If the intention is to create a new product, a question arises: why explicitly set the product_id in your new action? Typically, the database will handle setting the ID when creating a new instance of the Product model. Manual ID setting can lead to race conditions.

In addition, concerning the JavaScript aspect: why utilize it? Instead, you can incorporate different checkboxes styled according to your preferences using CSS (e.g., color changes for checked state). Assign relevant names to these checkboxes based on the steps (e.g., Hydratacao, nutricao) and check their presence in the create action with parameters such as

params[:product][:nutricao].present?
. Ensure all steps are collected in the new action by executing @steps = Step.all rather than @steps = Array.new(), facilitating checkbox creation through iteration.

Lastly, within the create action, it is advised to create a new object instead of instantiating one. Therefore, consider utilizing

@product = Product.create(product_params)
instead of
@product = Product.new(product_params)
. Additionally, manual addition of steps may be necessary since it might not work via whitelisting, but experimentation can validate this approach.

(Friendly tip: embark on the beginner tutorial available at http://guides.rubyonrails.org/getting_started.html to gain better understanding of Rest and Crud concepts).

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

The overflow of Highcharts tooltips is set to be hidden

My issue arises when the chart drawing area is smaller than a highchart tooltip, causing part of the tooltip to be hidden as it overflows the chart. I would like the tooltip to remain visible at all times, regardless of the size of the chart area. I have ...

What could be the reason these two functions yield different outcomes?

I am currently in the process of optimizing a function to enhance performance. Previously, the old function took approximately 32 seconds, while the new one now only takes around 350 milliseconds for the same call. However, there seems to be an issue as th ...

Can you guide me on how to access an Angular route using a URL that includes query parameters?

Within my current development project, I have implemented a user profile route that dynamically navigates based on the user's _id. This means that when a user accesses the page, their _id is stored in localStorage and then used to query MongoDB for th ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

React - Unable to access variables that are not defined (trying to access 'params')

Someone else had a similar question regarding this tutorial, but unfortunately I am struggling with this more advanced section. An error occurred: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'params') at fetc ...

Transferring data from JavaScript variables to PHP function through AJAX requests

Within my dashboard.php, there is a JavaScript function triggered by a button click event named getTeamMembers. This function receives values from the user's interaction and passes them to a PHP function also present in dashboard.php. Despite my effo ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...

Stop ajax loading animation for a specific scenario

I usually have a global ajax load animation that runs during every ajax call. However, there are certain cases where I need to disable this effect. How can I achieve that? This is the code for the global animation : $(document).ajaxStart(function(){ $ ...

What is the importance of using a polyfill in Babel instead of automatically transpiling certain methods?

Recently, I have been diving into a course that delves into the use of babel in JavaScript. It was explained to me that babel, with the preset "env," is able to transpile newer versions of ES into ES5. However, I found myself facing a situation where the a ...

Accessing website login - <div> and validating user entry

I am currently working on developing a basic login webpage, but I am facing issues with the rendering of the page. Below is the code I am using: function logIn(username, password){ var username = document.getElementById("username").value; var p ...

"Exploring the capabilities of articles, users, comments, and AJAX

After successfully building an app using RAILS 4 with tables such as users, comments, and articles, I encountered an issue. When creating comments via ajax, a strange duplication occurs. The first comment is created successfully, but subsequent comments di ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

Enhancing User Experience with AJAX-loaded Navigation Bar

I have set up the following structure: A main-page.php consisting of: 1) A header 2) A navigation bar 3) Content (loaded inside a <div id="dynamic-content"></div>) 4) Footer The navigation bar contains various options (e.g. About Us, Cont ...

Initiate automatic playback of audio on website following a delay

I attempted to change the state of play from false to true and also experimented with adding ComponentDidMount,ComponentDidUpdate, and ComponentWillMount but unfortunately, nothing seemed to solve the issue. I consistently encountered errors at different p ...

Is there a way for me to showcase the most recently added item above the existing one?

Is there a way to show the most recently added item at the top of the list instead of at the bottom? <div className="App"> <h2>{this.state.title}</h2> <form ref="myForm" className="myForm"> <input type="tex ...

moving a simulated element to a new location

Looking for some help with my html/CSS code that creates a unique element at the bottom of a div with an image background. The shape I've created is positioned at the bottom of the div... Below is the HTML: <div style="background-image:url(&apos ...

Problem related to permissions within a node.js package

Introducing my newly built npm module called emeraldfw, now available for public use. Here is a glimpse of the contents in my package.json file: { "name": "emeraldfw", "version": "0.6.0", "bin": "./emeraldfw.js", "description": "Emerald Framework ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...