2016-09-06 5 views
0

Michael Hartl의 튜토리얼을 따르면서 몇 가지 문제가 발생한 장바구니를 만들었습니다.ruby ​​on rails, cart & current_user와 관련한 문제

  1. 각 사용자는 다른 'ID'로 새로운 쇼핑 카트를 만들 수 있지만 다른 사용자가 장바구니에 제품을 추가하면 추가 된 제품은 CURRENT_USER

    에 의해 대신 특정 카트의 다른 'ID'의 모든 카트에 추가
  2. 다른 사용자 카트를 볼 수 없어도 자신의 장바구니만을 보도록 제한하는 방법은 무엇입니까?

덕분에 많은 감사를드립니다.

user.rb은 (하지가 길어질 수 있기 때문에 완전한 코드는 추가 : 마이클 하틀 튜토리얼에서 원래 코드 외에 'has_one 카트')

class User < ActiveRecord::Base 
attr_accessor :remember_token, :activation_token, :reset_token 
before_save :downcase_email 
before_create :create_activation_digest 
has_many :orders 
has_one :cart 

cart.rb

class Cart < ActiveRecord::Base 
has_many :line_items, dependent: :destroy 
belongs_to :user 

def add_product(product_id) 
    current_item = line_items.find_by(product_id: product_id) 
     if current_item 
      current_item.quantity += 1 #quantity of line_item, product in cart 
     else 
      current_item = line_items.build(product_id: product_id) 
     end 
    current_item 
end 


def total_price 
    line_items.to_a.sum { |item| item.total_price } 
end 
end 

우려/Current_Cart.rb

,

line_items_controller.rb

class LineItemsController < ApplicationController 
include CurrentCart 
before_action :set_cart, only: [:create] #before create, execute :set_cart, find(or create) cart 
before_action :set_line_item, only: [:show, :edit, :update, :destroy] 


def index 
    @line_items = LineItem.all 
end 

def show 
end 

def new 
    @line_item = LineItem.new 
end 

def edit 
end 

def create 
product = Product.find(params[:product_id]) 
@line_item = @cart.add_product(product.id) 
    if @line_item.save 
    redirect_to current_user.cart 
    else 
    render :new 
    end 
end 

def update 
    if @line_item.update(line_item_params) 
    redirect_to @line_item, notice: 'Line item was successfully updated.' 
    else 
    render :edit 
    end 
end 

def destroy 
@line_item.destroy 
    redirect_to line_items_url, notice: 'Line item was successfully destroyed.' 
end 

private 
def set_line_item 
    @line_item = LineItem.find(params[:id]) 
end 

def line_item_params 
    params.require(:line_item).permit(:product_id) 
end 
end 

carts_controller.rb 메신저 ID가 '1'나 'ID가 쇼핑 카트를 생성 한 사용자로 로그온하는 경우

class CartsController < ApplicationController 
before_action :set_cart, only: [:edit, :update, :destroy] 
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart 


def show 
    @cart = current_user.cart 
end 

def edit 
end 


def update 
    if @cart.update(cart_params) 
    redirect_to @cart, notice: 'Cart was successfully updated.' 
    else 
    render :edit 
    end 
end 


def destroy 
    @cart.destroy if @cart.id == session[:cart_id] 
    session[:cart_id] = nil 
    redirect_to store_url 
end 

private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_cart 
    @cart = Cart.find(params[:id]) 
end 

# Never trust parameters from the scary internet, only allow the white list through. 
def cart_params 
    params.fetch(:cart, {}) 
end 

def invalid_cart 
    logger.error "Attempt to access invalid cart #{params[:id]}" 
    redirect_to store_url, notice: 'Invalid cart' 
end 
end 
+0

"Michael Hartl의 튜토리얼을 따르고 장바구니를 만들었습니다."장바구니를 만드는 Michael Hart의 책은 기억하지 않습니다. 그러나 이것은 Agile Web Development with Rails 책을 떠올리게합니다. 그렇다면 "다른 사용자 카트를 볼 수 없어도 자신의 장바구니만을 보도록 제한하는 방법"이라고 표시되는 경우 결과가 어떻게 나타날지 이해할 수 없습니다. 내 repo를 보았고'current_cart.rb' 코드가 정확하다고 보입니다. – fbelanger

+0

예. 기본적으로 두 자습서 (사용자 로그인/민첩 개발에서 전자 상거래 로그인), 예를 들어 사용자가 '1'ID로 로그인 한 경우 ID가 '1'인 장바구니를 만들었습니다. 로그 아웃 한 다음 ID가 '2'인 다른 계정으로 다시 로그인하고 ID가 '2'인 장바구니를 만들었지 만 링크 카트/1이있는 다른 장바구니에 액세스 할 때 여전히 다른 사용자의 장바구니를 볼 수 있습니다. 일어날 것입니다. 희망을 이해합니다 –

답변

0

1'. 로그 아웃 한 다음 ID가 '2'인 다른 계정으로 다시 로그인하고 ID가 '2'인 장바구니를 만들었지 만 링크 카트/1이있는 다른 장바구니에 액세스 할 때 여전히 다른 사용자의 장바구니를 볼 수 있습니다. 일어날 것입니다. 희망을 이해하십시오 -

다른 개인 카트를 볼 수있는 이유는 컨트롤러 코드 때문입니다.

카트가있을 때마다 컨트롤러는 먼저 컨트롤러 내에 set_cart을 사용하여 카트를 설정합니다.

def set_cart 
    @cart = Cart.find(params[:id]) 
end 

이렇게하면 특정 ID가있는 장바구니를 가져옵니다.

그러면 show는 전달 된 카트를 표시합니다. 당신이 카트를 설정하고 컨트롤러에서 기존 set_cart을 제거 current_cart.rb을 사용하는 일을해야 무엇

def show 
    @cart = current_user.cart 
end 

. 또한 current_cart.rbset_cart을 공개합니다.

또한 경로를 변경해야합니다 (:id이 예상되므로). 이제는 어떤 카트를 볼 것인지 서버에 알려주지 않습니다.

정확히 CurrentCart이 어디에 포함되어 있는지 잊어 버렸습니다. ApplicationController에 있었던 것 같습니다. 그렇다면 before_action :set_cart, only[...]은 다른 로직과 잘 작동해야합니다.

+0

안녕하세요 @ fbelanger, 고마워요, 나중에 좀 고쳐. 또 다른 문제는 현재 사용자 카트를 볼 때마다, URL은'http : // localhost : 3000/cart.84'이고'http : // localhost : 3000/cart'로 어떻게 바꿀 수 있습니까? –

+0

경로가 작동하는 방식을 변경하고 ERB 파일 내의 경로를 변경해야합니다. – fbelanger