无方法错误,无法将数据保存到模型

时间:2016-10-12 16:10:26

标签: ruby-on-rails ruby-on-rails-4

我在尝试将数据保存到数据库时遇到了一些问题。该错误始终指向CREATE操作@invoices = @ permits.build_invoice()。声明未定义的方法`build_invoice'为nil:NilClass NO METHOD ERROR。任何人都知道如何解决它?

class InvoicesController < ApplicationController

  def new
    @permits = Permit.find(params[:permit_id])
    @invoice = Invoice.new
  end

  def create
    #@current_user = User.find_by(id: session[:user_id])

    @invoices = @permits.build_invoice(invoice_params)
    if @invoices.save
      redirect_to payment_path
    else

    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_invoice
    @invoice = Invoice.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def invoice_params
    params.require(:invoice).permit(:vehicle_type, :name, :department, :carplate, :duration, :permitstart, :permitend, :price, :time)
  end
end

Permit.rb

class Permit < ApplicationRecord
  belongs_to :user
  has_one :invoice
end

Invoice.rb

class Invoice < ApplicationRecord
  belongs_to :user
  has_one :receipt
  belongs_to :permit
end

3 个答案:

答案 0 :(得分:0)

@permits是零。您还没有为该变量分配任何内容。 根据您的型号,它也应该是1张许可证和1张发票。

def create
  @permit = Permit.find(params[permit_id])
  @invoice = @permit.invoice.new(invoice_params)
  if @invoices.save
    redirect_to payment_path
  else
    #catch error here
  end
end

答案 1 :(得分:0)

@permits范围内没有create。因此,您可以使用控制器过滤器查找@permitsnew

create
class InvoicesController < ApplicationController
  before_action :find_permit, only: [:new, :create]

  def new
    # Remove it @permits = Permit.find(params[:permit_id])
    @invoice = Invoice.new
  end

  # your other codes

  private

  def find_permit
    @permits = Permit.find(params[:permit_id])
  end
end

顺便说一句,你应该将@permits重命名为@permit,单数形式更有意义!

答案 2 :(得分:0)

从您的视图/ API调用中传递permit_id

更改您的创建方法,如下所示。

  def create
    #@current_user = User.find_by(id: session[:user_id])

    @permit = Permit.find(params[:permit_id])
    @invoices = @permit.build_invoice(invoice_params)
    if @invoices.save
      redirect_to payment_path
    else

    end
  end