我想在显示页面上显示日托详细信息,但出现此错误

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)。

您也可以只使用:

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


如果按ID搜索。或者,如果您需要检查其用户day_care

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

09-25 18:13