用于nil的Ruby未定义方法`user':NilClass

时间:2015-05-17 01:08:53

标签: ruby-on-rails ruby activerecord

我正在关注构建rails存储的关于+的教程,但是我收到了错误。我几次检查我的颂歌,但没有。感谢您的帮助

我的order_controller.rb(第21行 - 错误)

CONCURRENT_TRANSACTION

order.rb

class OrdersController < ApplicationController
before_filter :initialize_cart

def create
    @order_form = OrderForm.new(
        user: User.new(order_params[:user]),
        cart: @cart
    )

    if @order_form.save
        notify_user
        redirect_to root_path, notice: "Thank you for placing the order."
    else
        render "carts/checkout"
    end
end

private

def notify_user
    @oder_form.user.send_reset_password_instructions
    OrderMailer.order_confirmation(@order_form.order).deliver
end

def order_params
    params.require(:order_form).permit(
        user: [ :name, :phone, :address, :city, :country, :postal_code, :email ]
    )
end

order_form.rb

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :order_items

  def total_price
    order_items.inject(0) { |sum, item| sum + item.total_price }
  end
end

order_confirmation.text.erb

class OrderForm
include ActiveModel::Model

attr_accessor :user, :order
attr_writer :cart

def save
    set_password_for_user

    if valid?
        persist
        true
    else
        false
    end
end

def has_errors?
    user.errors.any?
end 

private

def valid?
    user.valid?
end

def persist
    user.save
    @order = Order.create! user: user

    build_order_items
end

def set_password_for_user
    user.password = Digest::SHA1.hexdigest(user.email + Time.now.to_s)[0..8]
end

def build_order_items
    @cart.items.each do |item|
        @order.order_items.create! product_id: item.product_id, quantity: item.quantity
    end
end

1 个答案:

答案 0 :(得分:2)

你在第21行写的@oder_form.user.send_reset_password_instructions应该@order_form.user.send_reset_password_instructions你错过了一个顺序