초보자로서 나는 사용자 ID를 Line_Items 테이블로 가져올 수 있었기 때문에 현재 사용자 세션 ID를 다른 테이블에 저장하는 것이 쉬울 것이라고 생각했다. 나는 내 키가 다른 테이블에 하나의 프라이 머리 키를 저장하는 기본 원칙을 이해하지 못했다고 생각한다. 나의 키가 카트 User_ID를 Carts 테이블에 저장하려고하는 외래 키는 카트에 속하고 카트에는 많은 카트가있다. 이 질문과 관련된 모든 코드 또는 유용한 링크는 크게 감사하겠습니다. 다음은 내 모델입니다. 도움이 필요한 다른 코드가 있으면 알려주십시오. 감사합니다 :루비 레일에 외래 키로 다른 테이블에 사용자 ID를 저장하는 기본 규칙
class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :role, :subscriber, :name
has_many :line_item
has_many :cart
class NotAuthorized < StandardError; end
end
Cart.rb :
class Cart < ActiveRecord::Base
attr_accessible :user_id
has_many :line_items, dependent: :destroy
belongs_to :user
def add_phone(phone, current_user = nil)
current_item = line_items.find_or_initialize_by_phone_id(phone.id)
current_item.increment!(:quantity)
current_item.phone.decrement!(:stock)
current_item.user = current_user
current_item.phone.save
current_item
end
# returns true if stock level is greater than zero
def can_add(phone)
phone.stock > 0
end
# returns the total number of items in a cart
def number_of_items
total = 0
line_items.each do |item|
total += item.quantity
end
total
end
def empty?
number_of_items == 0
end
def grand_total
grand_total = 0
line_items.each do |item|
grand_total += item.quantity * item.phone.price
end
grand_total
end
end
어떤 오류가 발생 했습니까? –
오류가 발생하지 않습니다. 실제로 레일에서 루비의 외래 키로 기본 키를 다른 테이블에 가져 오는 방법을 전혀 모릅니다. –