【发布时间】:2016-02-27 20:18:51
【问题描述】:
我开始学习 ruby 并开始爱上它,但是我有一个我自己无法解决的问题。
我无法使用已创建的模型在数据库中查找或创建数据,出现错误NoMethodError: undefined method 'create' for Stuff:Module
模型类很简单:
class Stuff < ActiveRecord::Base
validates :name, presence: true
end
宝石文件
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use mysql as the database for Active Record
gem 'mysql2', '0.3.18'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
迁移文件:
class Stuff < ActiveRecord::Migration
def change
create_table :stuffs do |t|
t.string :name
end
add_index :stuffs, :id
end
end
控制器:
class StuffsController < ApplicationController
before_action :get_stuffs, :only => [:index, :show]
before_action :validate_params, :only => [:create]
def get_stuffs
@stuffs = []
end
def show
end
def index
end
def create
Stuff.create(params[:name])
end
private
def validate_params
params.require(:name)
end
end
这不仅适用于 create 方法,还适用于任何其他方法,例如 find、first 或 all.
我从控制器调用任何方法都收到此错误,但也来自例如seed.rb。
我确定这是一个愚蠢的新手问题,但我不知道如何解决这个问题......
谢谢!
【问题讨论】:
-
请注意,错误消息显示的是
Stuff:Module,而不是Stuff:Class- 除了您的课程之外,您还有Stuff模块吗? -
我没有为该类创建任何模块,rails 教程没有提到我必须这样做,是吗?
-
什么时候出现错误?你能在 Rails 控制台中创建一个 Stuff 对象吗?如果您无法在控制台中创建 stuff 对象,请发布 stuff 表的迁移文件的内容。另外,发布 StuffController。
-
我从控制器方法、执行 rake db:seed 或从控制台调用 Stuff.create 得到错误。我用控制器和迁移文件更新了帖子。
-
@frostering - 你的应用程序中是否有一个名为 stuff 的文件夹?
标签: ruby-on-rails ruby