未定义的局部变量或方法

时间:2014-07-20 17:32:16

标签: ruby-on-rails ruby 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

这是show.html.erb:

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

以下是路线:

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

以下是schema.rb中的内容:

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

它保存到数据库并在创建后重定向到根路径并且就此而言。我做错了什么?

1 个答案:

答案 0 :(得分:3)

  

未定义的局部变量或方法`yoga'

错误是因为您使用的是yoga而不是@yogashow.html.erb中的代码应该如下所示

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

因为您在控制器的@yoga中定义了show method实例变量。

另外,正如 @Iceman 指出的那样,@yoga = Yoga.update(yoga_params)方法中的这一行update看起来应该是@yoga = @yoga.update(yoga_params),而这一行{{您get 'show' => 'yogs#show'中的1}}应为routes