简体   繁体   English

Ruby on Rails Controller中没有方法错误,尝试创建记录

[英]Ruby on Rails No Method Error in Controller, trying to create a record

I've got a ruby on rails application and am trying to save category data to the system, but whenever I click save I get the error: 我在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

This is my code in the categories_controller.rb: 这是我在category_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

Can someone please help me. 有人可以帮帮我吗。

You should update the code from the comments in your question, because your model has a clear mistake in it: 您应该从问题的注释中更新代码,因为您的模型存在明显的错误:

Your code: 您的代码:

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 

If you take a look at the validation, you are trying to validate category itself instead of whatever it is you need to validate(from your previously posted code it looks like you need to validate genre ) 如果您查看验证,则尝试验证category本身,而不是验证所需的category (从先前发布的代码中看来,您需要验证genre

For your code to work, you need to change it to this: 为了使代码正常工作,您需要将其更改为:

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

You use validations on attributes( like genre in your case), not the object itself. 您对属性(例如您的情况下的genre )使用验证,而不是对象本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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