ruby - Rails connect modal with a create action -
it's first post. i'm new in rails , need help. try make online shop. have create button "buy" (with bootstrap) under each of products, activate modal. inside modal button "add cart", , cant make work. want through create action in line_items_controller add line_item cart. modal works fine button "add cart" no. think problem path give button.
my code:
cart.rb
class cart < activerecord::base has_many :line_items, dependent: :destroy
line_item.rb
class lineitem < activerecord::base belongs_to :product belongs_to :cart
product.rb
class product < activerecord::base has_many :line_items
line_items_controller.rb
class lineitemscontroller < applicationcontroller include currentcart before_action :set_cart, only: [:create] before_action :set_line_item, only: [:show, :edit, :update, :destroy] def create @product = product.find(params[:product_id]) @line_item = create_line_items(@product) respond_to |format| if @line_item.save format.html { redirect_to @line_item.cart, notice: 'line item created.' } format.json { render :show, status: :created, location: @line_item } else format.html { render :new } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end private def set_line_item @line_item = lineitem.find(params[:id]) end def line_item_params params.require(:line_item).permit(:product_id, :cart_id) end
app/controllers/concerns/current_cart.rb
module currentcart extend activesupport::concern def create_line_items(product) @cart.line_items.build(product: product) end private def set_cart @cart = cart.find(session[:cart_id]) rescue activerecord::recordnotfound @cart = cart.create session[:cart_id] = @cart.id end end
the modal in application.html.erb
<div class="modal fade" id="buymodal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <p>are sure want buy this?</p> <%= button_to 'add cart', line_items_path(product_id: @product), :class => "btn btn-success glyphicon glyphicon-plus", data: {dismiss: "modal"} %> </div> </div> </div> </div>
and button 'buy' trigger modal.
views/products/index.html.erb
<%= link_to 'buy', '#', class: "btn btn-success active", data: { toggle: "modal", target: "#buymodal"} %>
i appreciate help!
the problem seems me method type. try use ':method => :post' button_to tag.
<%= button_to 'add cart', line_items_path(product_id: @product), :method => :post, :class => "btn btn-success glyphicon glyphicon-plus", data: {dismiss: "modal"} %>
Comments
Post a Comment