我在rails应用程序上有一个ruby,我正在尝试将类别数据保存到系统中,但每当我点击保存时我都会收到错误:
NoMethodError in CategoriesController#create
undefined method `category' for #<Category id: nil, genre: "", created_at: nil, updated_at: nil>
Extracted source (around line #29):
27 def create
28 @category = Category.new(category_params)
29 if @category.save
30 redirect_to @category, notice: 'Category was successfully created.'
31 else
32 render action: 'new'
Rails.root: C:/Sites/week_15/New/my_bookshop_test2 _basic
这是我在categories_controller.rb中的代码:
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
if @category.save
redirect_to @category, notice: 'Category was successfully created.'
else
render action: 'new'
end
end
有人可以帮帮我吗。
答案 0 :(得分:0)
您应该更新问题中的评论代码,因为您的模型中存在明显的错误:
您的代码:
class Category < ActiveRecord::Base
has_many :products
validates :category, :presence => { :message => "cannot be blank ..."}
# display id and genre text e.g. 1 Detective, 2 Science Fiction, etc.
# used in category drop down selection box
def category_info
"#{id} #{genre}"
end
end
如果您查看验证,那么您正在尝试验证category
本身而不是验证所需的内容(从您之前发布的代码看起来您需要验证genre
)
要使您的代码正常工作,您需要将其更改为:
class Category < ActiveRecord::Base
has_many :products
validates :genre, :presence => { :message => "cannot be blank ..."}
# display id and genre text e.g. 1 Detective, 2 Science Fiction, etc.
# used in category drop down selection box
def category_info
"#{id} #{genre}"
end
end
您对属性(例如您的genre
)使用验证,而不是对象本身。