As a newbie, I thought it would be easy to store the current user session ID in another table, since I managed to get the user ID in the Line_Items table, but I believe that I did not understand the basic principle of storing one primary key in another table as a foreign key, which in my case, it tries to save the User_ID session in the Carts table, since the basket belongs to the user, and the user has many carts. Any code or any useful link on this subject would be greatly appreciated. Below are my models. Please let me know if any other code is needed for help. Thank:
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
def can_add(phone)
phone.stock > 0
end
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