简体   繁体   中英

Basic rule to store User ID into another table as foreign key in ruby on rails

As a beginner I thought that it would be easy to store current user session ID into another table as I managed to get the user ID into Line_Items table however I believe that I have not understood the basic principle of storing one primary key into another table as a foreign key which in my case is trying to store session User_ID into Carts table as a cart belongs to a user and user has many cart. Any code or any helpful link regarding this question will be greatly appreciated. Following are my models. Please let me know if any other code is needed for assistance. Thanks:

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

You have an error in your relationship declaration.. they should be plural, try that and see if it helps, also you should have an user_id on your carts & line items models.

has_many :line_items
has_many :carts

In User model

has_many :line_items
has_many :carts

Also in line Item and Cart model, you can mention:

belongs_to :user

We can mentioned it using :foreign_key as well given below:

belongs_to :user, foreign_key: "user_id"

Hope it will be helpful for you..

For getting session ID or for saving the records in your cart controller or line items controller

For LineItem

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

For Cart

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

For getting user id in your controller for finding related line_items and cart you can simply get it by current_user.id

In controllers or views for session id you can use as below

session['session_id']

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM