Shunan
Shunan

Reputation: 3264

How to pass value from input type in html to a controller in rails

I am beginner in html and ruby on rails. It sounds a very basic question but after many attempts I am not getting it how to pass value from a input type which is not in a form to a controller.

This is my code -

<div style = "border:1px solid black; padding:1em;">
    <%= link_to product.name, product_path(product.id) %>
    <br><br>

    Price : <%= product.price %>

    Quantity : <input type="text" name='quantity' value = '1' min ='1'/>
    <br><br>

    <% if session[:cart_id] && @cart_item_ids.include?(product.id) %>
    <button><%= link_to 'Remove', remove_item_path(:product_id => product.id)
    %></button>
    <% elsif session[:cart_id] %> 
    <button><%= link_to 'Add To Cart', add_to_cart_path(:product_id => product.id, :price => product.price, :quantity => 'quantity')
    %></button>
    <% end%>
  <br>
</div>

This is my controller

class CartsController < ApplicationController

  def add_to_cart
    byebug
    cart_item = CartItem.new
    cart_item.product_id = params[:product_id]
    cart_item.quantity = 1
    cart_item.price = params[:price]
    cart_item.cart_id = session[:cart_id]
    cart_item.save

    product = Product.find(params[:product_id])
    category = Category.find(product.category_id)

    redirect_to category_path(:id => product.category_id)
  end

  def remove_item
    CartItem.where(:cart_id =>  session[:cart_id]).where(:product_id => params[:product_id]).first.destroy
    product = Product.find(params[:product_id])
    redirect_to category_path(:id => product.category_id)
  end

  def view_cart
    cart = Cart.where(:consumer_id => session[:consumer_id]).first
    @cart_items = CartItem.where(:cart_id => cart.id)
    render 'show'
  end

end

Thanks in advance.

Upvotes: 0

Views: 339

Answers (1)

Willem Ellis
Willem Ellis

Reputation: 5016

You either need to use a form to post the data, or you need to use some asynchronous Javascript request to post the data.

Upvotes: 1

Related Questions