NoMethodError : undefined 方法 'find' for nil:NilClass



我想在显示页面上显示日托的详细信息,但是我得到了这个错误

NoMethodError : undefined method `find' for nil:NilClass

从日托控制器文件,我没有得到任何想法。

这是我的控制器文件
class DayCaresController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_day_care, only: [:show, :edit, :update, :destroy]
 # GET /day_cares
 # GET /day_cares.json
 def index
  @day_cares = DayCare.all
 end
 # GET /day_cares/1
 # GET /day_cares/1.json
 def show
 end
 # GET /day_cares/new
 def new
   @day_care = DayCare.new
 end
 # GET /day_cares/1/edit
 def edit
 end
 # POST /day_cares
 # POST /day_cares.json
 def create
   @day_care = current_user.build_day_care(day_care_params)
  respond_to do |format|
    if @day_care.save
      UserMailer.welcome_email(@user).deliver
      format.html { redirect_to @day_care, :gflash => { :success => 'Day care was successfully created.'} }
      format.json { render :show, status: :created, location: @day_care }
    else
      format.html { render :new }
      format.json { render json: @day_care.errors, status: :unprocessable_entity }
    end
  end
end
# PATCH/PUT /day_cares/1
# PATCH/PUT /day_cares/1.json
def update
  respond_to do |format|
    if @day_care.update(day_care_params)
      format.html { redirect_to @day_care, :gflash => { :success => 'Day care was successfully updated.'} }
      format.json { render :show, status: :ok, location: @day_care }
    else
      format.html { render :edit }
      format.json { render json: @day_care.errors, status: :unprocessable_entity }
    end
  end
end
# DELETE /day_cares/1
# DELETE /day_cares/1.json
def destroy
  @day_care.destroy
  respond_to do |format|
    format.html { redirect_to day_cares_url, :gflash => { :success => 'Day care was successfully destroyed.'} }
    format.json { head :no_content }
  end
end
private
  # Use callbacks to share common setup or constraints between actions
  def set_day_care
    @day_care = current_user.day_care.find(params[:id]) # => **I got error this line**
  end
  # Never trust parameters from the scary internet, only allow the white list through.
  def day_care_params
    params.require(:day_care).permit(:name, :address, :office_phone, :cell_phone, :logo, :website, :user_id)
  end
  def dashboard
  end
  def profile
  end
 end

如果用户has_many: day_cares使用此名称而不是day_care:

@day_care = current_user.day_cares.where(id: params[:id]).take

或者像你写的那样:

@day_care = current_user.day_cares.find(params[:id])

但是用数组代替单实例(day_cares)。

也可以用just:

@day_care = DayCare.find(params[:id])

如果按id搜索。或者如果您需要检查它的用户day_care:

@day_care = DayCare.where(id: params[:id], user: current_user).take

current_user.day_care.find不可用,因为您只能对多个关联执行查询。因此,假设模型关联正确设置为:

class User < ActiveRecord:Base
  has_many :day_cares
  ...
end

解决方案可能只是解决

的拼写错误
`current_user.day_care.find` #wrong!

`current_user.day_cares.find` #right!

相关内容

最新更新