【问题标题】:private method `main_image' called for nil:NilClass? how to fix私有方法“main_image”调用了 nil:NilClass?怎么修
【发布时间】:2017-06-28 22:00:56
【问题描述】:

portfolios_controller.rb

class PortfoliosController < ApplicationController
  def index
    @portfolio_items = Portfolio.all 
  end

  def new
    @portfolio_item =Portfolio.new
  end

  def create
    @portfolio_item =Portfolio.new(params.require(:portfolio).permit(:title, :subtitle, :body))

    respond_to do |format|
      if @portfolio_item.save
        format.html { redirect_to portfolios_path, notice: 'Your Portfolio Item is now live.' }
        format.json { render :show, status: :created, location: @blog }
      else
        format.html { render :new }
        format.json { render json: @blog.errors, status: :unprocessable_entity }
      end
    end
  end

  def edit
    @portfolio_item = Portfolio.find(params[:id])
  end

  def update
    @portfolio_item = Portfolio.find(params[:id])
    respond_to do |format|
      if @portfolio_item.update(params.require(:portfolio).permit(:title, :subtitle, :body))
        format.html { redirect_to portfolios_path, notice: 'The record successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end 
end

def show
   @portfolio_item = Portfolio.find(params[:id])
end

show.html.erb

<%= image_tag @portfolio_item.main_image %>

<h1><%= @portfolio_item.title %></h1>

<em><%= @portfolio_item.subtitle %></em>

<p><%= @portfolio_item.body %></p>

【问题讨论】:

  • 请发布您的Portfolio 模型。
  • 欢迎来到 SO,尝试提供有关您的问题的所有信息(在这种情况下,完整的错误消息会有所帮助)。
  • 我修正了您的缩进,这表明您的 show 操作不在课程范围内。您需要解决该问题,然后查看问题是否仍然存在。

标签: ruby-on-rails ruby methods


【解决方案1】:

添加show 操作

def show
  @portfolio_item = Portfolio.find(params[:id])
end

在你的portfolios_controller

【讨论】:

    【解决方案2】:

    为 nil:NilClass 调用了私有方法 `main_image'?

    您在show 方法之前结束课程 PortfoliosController,因此它失去了作用域。把它放在PortfoliosController

    def update
      @portfolio_item = Portfolio.find(params[:id])
      respond_to do |format|
        if @portfolio_item.update(params.require(:portfolio).permit(:title, :subtitle, :body))
          format.html { redirect_to portfolios_path, notice: 'The record successfully updated.' }
        else
          format.html { render :edit }
        end
      end
    end 
    
    def show
       @portfolio_item = Portfolio.find(params[:id])
    end
    end #class end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多