NoMethodError:nil的未定义方法`find':NilClass

时间:2014-06-20 10:26:18

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

我想在展会页面上显示日托详情,但我收到了此错误

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

2 个答案:

答案 0 :(得分:3)

如果用户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

答案 1 :(得分:0)

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!