为什么我在 Ruby 中收到 NoMethodError?

Why am I getting a NoMethodError in Ruby?

我目前正在开发食谱盒应用程序,在 rails 上使用 ruby。当我想创建一个新食谱时它说

undefined method `title'

= f.input :title, input_html: { class: 'form-control' }

这是我的form.html.haml

= simple_form_for @recipe, html: { multipart: true } do |f|
    - if @recipe.errors.any?
        #errors
            %p
                = @recipe.errors.count
                Prevented this recipe from saving
            %ul
                - @recipe.errors.full_messages.each do |msg|
                    %li= msg
    .panel-body
        = f.input :title, input_html: { class: 'form-control' }
        = f.input :description, input_html: { class: 'form-control' }

    = f.button :submit, class: "btn btn-primary"

这是我的 recipes_controller.rb

class RecipesController < ApplicationController
before_action :find_recipe, only: [:show, :edit, :update, :destroy]

def index
end

def show
end

def new
    @recipe = Recipe.new
end

def create
    @recipe = Recipe.new(recipe_params)

    if @recipe.save 
        redirect_to @recipe, notice: "Toll! Neues Rezept erfolgreich erstellt."
    else
        render 'new'
    end
end

private

def recipe_params
    params.require(:recipe).permit(:title, :description)
end

def find_recipe
    @recipe = Recipe.find(params[:id])
end

结束

  1. 您必须在 'new' 视图中呈现表单
  2. 您的数据库中必须有列 'title'

让我们看看 'debug @recipe' 打印了什么,有没有 'title' 属性?