The basic rule for storing the user ID in another table as a foreign key in ruby โ€‹โ€‹on rails

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

# 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
+3
2

. , , , user_id .

has_many :line_items
has_many :carts
+1

has_many :line_items
has_many :carts

:

belongs_to :user

, : foreign_key:

belongs_to :user, foreign_key: "user_id"

, .

LineItem

#In create action
@line_item = current_user.line_items.build(params[:user])
# or
@line_item.user = current_user

#In create action
@cart = current_user.carts.build(params[:user])
# or
@cart.user = current_user

user id line_items and cart current_user.id

session['session_id']

.

+1

All Articles