无法创建数据rails,没有方法错误

时间:2016-10-09 10:12:37

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

我正在使用Ruby on Rails实现一个网站。我遇到了麻烦,我无法创建新数据并保存到我的模型中。我得到的错误是错误指向@vpermits = current_user.vpermits.build(vpermit_params)。任何人都知道我做错了什么?

NoMethodError in VisitorPermitsController#create
undefined method `vpermits' for #<User:0x9b7b478>


    def create
        @vpermits = current_user.vpermits.build(vpermit_params)
        if @vpermits.save
          redirect_to @vpermits
        else

这是我的visitor_permits_controller.rb

class VisitorPermitsController < ApplicationController
    before_action :set_vpermit, only: [:destroy]
    def index
      @vpermits = VisitorPermit.where(:user_id => current_user.id)
    end

    def new
      @vpermits = VisitorPermit.new
    end

    def create
        @vpermits = current_user.vpermits.build(vpermit_params)
        if @vpermits.save
          redirect_to @vpermits
        else
          render 'new'
        end
      end


    def destroy
      VisitorPermit.destroy_all(user_id: current_user)
      respond_to do |format|
        format.html { redirect_to root_path, notice: 'Permit was successfully canceled.' }
        format.json { head :no_content }
      end
    end

    def show
      @vpermits = VisitorPermit.find(params[:id])
    end

    def update
      @vpermits = VisitorPermit.where(user_id: current_user).take
      respond_to do |format|
        if @vpermits.update(vpermit_params)
          format.html { redirect_to root_path}
          flash[:success] = "Permit successfully updated"
          format.json { render :show, status: :ok, location: @user }
        else
          format.html { render :edit }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end

    def edit
      @vpermits = VisitorPermit.find(params[:id])
    end

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

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

1 个答案:

答案 0 :(得分:1)

您的代码可能会在UserVistorPermit模型之间建立关联(has_many)。并且您将模型名称设为VistorPermit。所以 buliding的代码行应该是这样的:

@vpermits = current_user.vistor_permits.build(vpermit_params)