ruby-on-rails - 在 ruby​​ on rails 中将用户 ID 作为外键存储到另一个表中的基本规则

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

作为初学者,我认为将当前用户 session ID 存储到另一个表中会很容易,因为我设法将用户 ID 放入 Line_Items 表中,但是我相信我还没有理解将一个主键存储到另一个表中的基本原理另一个表作为外键,在我的例子中,它试图将 session 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

购物车.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

最佳答案

你的关系声明有误。他们应该是复数,试试看是否有帮助,你的购物车和订单项模型上也应该有一个 user_id。

has_many :line_items
has_many :carts

关于ruby-on-rails - 在 ruby​​ on rails 中将用户 ID 作为外键存储到另一个表中的基本规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740377/

相关文章:

ruby-on-rails - 在Ruby中将CSV header 转换为不区分大小写

ruby-on-rails - 地理编码器 gem 的 country_code 列表

ruby-on-rails - 如何在 Ruby 中使用常量进行映射

ruby - 如何在 Ruby 中使用 '~' 指定文件路径?

ruby-on-rails - 嵌套属性未正确显示表单

javascript - 如何从 Rails Controller 中的 XMLHttpRequest 中提取数据

ruby-on-rails - 如何编辑引用模型数据

ruby-on-rails - 什么 Ruby HTTP 守护进程为 Heroku Bamboo 应用程序提供支持?

ruby-on-rails - Rails 复选框可选区域

ruby - 如何在 Ruby 中获取类实例?