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.