ruby-on-rails - 创建行项目记录时将 session 用户 ID 添加到 Line_Items 表中 - Ruby on Rails

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

我正在尝试将用户 session ID 添加到 Line_Items 表中。我到处研究但找不到答案,这就是为什么必须将其发布在这里。此应用程序成功将电话 ID 和购物车 ID 添加到 Line_Items 表中,但当我尝试使用电话和购物车 ID 的类似方法时,不允许我添加用户 session ID。请参阅下面我当前的实现:

Line_Items Controller :

def create
  # current_cart method in application_controller.rb
  @cart = current_cart
  phone = Phone.find(params[:phone_id])
  if phone.stock > 0
    @line_item = @cart.add_phone(phone.id )
    if @line_item.save
      redirect_to  :back, notice: " '#{phone.model}'  has been added to your cart."
    else
      render action: "new" 
    end
  else
    redirect_to  :back, notice: " Cannot add: '#{phone.model}' - stock level is too low."
  end
end

Cart.rb 模型:

def add_phone(phone_id)
  current_item = line_items.find_by_phone_id(phone_id)
  if current_item
    current_item.quantity += 1
  else
    current_item = line_items.build(phone_id: phone_id)
    current_item.quantity = 1
  end
  current_item.phone.stock -= 1
  current_item.phone.save
  current_item
end

# returns true if stock level is greater than zero
def can_add(phone)
  phone.stock > 0
end

如果需要任何进一步的代码,请告诉我。

最佳答案

问题是 Rails 中的模型类对 Controller 和 session 一无所知。我假设您正在使用某种身份验证机制,在 session 中为您提供 current_user...因此我们必须将其放入您的 add_phone 方法中。

在 Controller 中,我会更改这一行:

@line_item = @cart.add_phone(phone.id)

对此:

@line_item = @cart.add_phone(电话, current_user)

(请注意,这里有两项更改 - 一项是传递电话而不是其 id,因为您已经找到了它,另一项是传递当前用户。

然后我们想将您的 add_phone 方法更改为如下所示:

def add_phone(phone, current_user = nil)
  # make sure your Item class initializes quantity to o, not 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

请注意,默认情况下我将用户设置为 nil...这样,您已有的不提供该字段的代码将继续工作。我还使用 find_or_initialize_by 帮助程序稍微简化了您的方法...避免了“if”测试。此外,递增和递减助手稍微清理了代码的意图。

您应该确保您的订单项类别包括

属于:用户

如果您发现自己需要了解 current_user 的大量域逻辑,您可能需要查看 Sentient_user gem。

关于ruby-on-rails - 创建行项目记录时将 session 用户 ID 添加到 Line_Items 表中 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650277/

相关文章:

ruby-on-rails-3 - 保存前使用回形针图像

ruby-on-rails - Ruby:-查找文件中某个字符的出现次数

javascript - 如果对象为空,则在 View 中有条件地显示元素

mysql - 无法从 Rails 应用程序连接到 Mysql

Ruby 和 SWIG 与 CMake

ruby 。无法添加来源

javascript - Ruby ajax js View 返回编码的 html 而不是有效的 html

ruby-on-rails - 从 Rails 4.2.1 升级

javascript - 为什么 Rails 不渲染 .js.erb 文件?

ruby-on-rails - Rails 7 + Devise + Turbo 流在登录时不显示错误