user3457760
user3457760

Reputation: 337

undefined local variable or method

I am trying to show an item I saved into the database and am getting the error

undefined local variable or method

Here is my controller:

class YogasController < ApplicationController
  before_action :authenticate_user!, :except => [:index, :show]

  def index
   @yoga = Yoga.all
  end

  def create
   @yoga = Yoga.new(yoga_params)
    if @yoga.save
      redirect_to yogas_path 
    else
        render action: 'new'
    end
  end

def update
 @yoga = Yoga.find(params[:id])
 @yoga = Yoga.update(yoga_params)
 redirect_to root_path 
end

def new
 @yoga = Yoga.new
end

def show
 @yoga = Yoga.find(params[:id])
end

def edit
 @yoga = Yoga.find(params[:id])
end

def destroy
 @yoga = Yoga.find(params[:id])
 @yoga.destroy
 redirect_to root_path
end 


private 
 def yoga_params
 params.require(:yoga).permit(:post, :title)
end  
end

Here is the show.html.erb:

<%= yoga.title %>
<%= yoga.post %>

Here are the routes:

 Rails.application.routes.draw do
 resources :yogas
 devise_for :users
 get 'show' => 'yogs#show'
 root 'yogas#index'
 end

Here is what I have in the schema.rb:

  create_table "yogas", force: true do |t|
     t.string   "title"
     t.string   "post"
     t.datetime "created_at"
     t.datetime "updated_at"
   end

It is saving to the DB and redirecting to the root path after it is made and thats about it. What am I doing wrong?

Upvotes: 0

Views: 1081

Answers (1)

Pavan
Pavan

Reputation: 33542

undefined local variable or method `yoga'

The error is because you are using yoga instead of @yoga.Your code in the show.html.erb should look like this

<%= @yoga.title %>
<%= @yoga.post %>

as you have @yoga instance variable defined in the show method of your controller.

And also,as pointed out by @Iceman,this line @yoga = Yoga.update(yoga_params)in your update method should look like this @yoga = @yoga.update(yoga_params),and this line get 'show' => 'yogs#show' in your routes should be get 'show' => 'yogas#show'

Upvotes: 3

Related Questions