将用户标识存储到另一个表中作为ruby on rails上的外键的基本规则

时间:2014-02-12 21:44:17

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

作为初学者,我认为将当前用户会话ID存储到另一个表中会很容易,因为我设法将用户ID存入Line_Items表但是我相信我还没有理解将一个主键存入的基本原则另一个表作为外键,在我的情况下试图将会话User_ID存储到Carts表中,因为购物车属于用户,用户有很多购物车。任何有关此问题的代码或任何有用的链接将不胜感激。以下是我的模特。如果需要任何其他代码,请告知我们。感谢:

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

2 个答案:

答案 0 :(得分:1)

你的关系声明中有错误..它们应该是复数,尝试一下,看看它是否有帮助,你的购物车上也应该有一个user_id。订单项型号。

has_many :line_items
has_many :carts

答案 1 :(得分:1)

用户模型

has_many :line_items
has_many :carts

同样符合商品购物车模式,您可以提及:

belongs_to :user

我们可以使用:foreign_key以及下面给出它:

belongs_to :user, foreign_key: "user_id"

希望它对你有所帮助..

获取会话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

获取它

在会话ID的控制器或视图中,您可以使用以下

session['session_id']

感谢。