简体   繁体   中英

private method `main_image' called for nil:NilClass? how to fix

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>

Add show action

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

In your portfolios_controller

private method `main_image' called for nil:NilClass?

You are ending the class PortfoliosController before show method, so it lost the scope. Put it inside the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM