Rails:NameError(未初始化的常量 UserSerializer) [英] Rails: NameError (uninitialized constant UserSerializer)
问题描述
我目前正在使用 Rails 6.0 构建一个仅限 Rails API 的应用程序.我正在使用 fast_jsonapi 进行 JSON:API 序列化 Ruby 对象.现在我只创建了 UsersController
.
I am currently building a Rails API-only application using Rails 6.0. I am using fast_jsonapi for JSON:API serialization of Ruby Objects. For now I have created only the UsersController
.
我有一个具有以下属性的 user
模型:
I have a user
model with the following attributes:
ActiveRecord::Schema.define(version: 2020_03_14_175719) do
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "username"
t.string "password_digest"
t.string "email"
t.string "phone"
t.text "address"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
end
我为它创建了一个 user_serializer
:
class UserSerializer
include FastJsonapi::ObjectSerializer
attributes :first_name, :last_name, :username, :password, :email, :phone, :address
end
我还通过 rails 控制台
在数据库上创建了一个 User
并包含以下信息:
I have also created a User
on the database via the rails console
with the following information:
User.delete_all
user = User.create! first_name: 'Promise', last_name: 'My last name', username: 'myusername', email: 'myemail@gmail.com', password: 'mypassword', phone: '002037363', address: 'my address'
puts "Created a new user: #{user.first_name} #{user.last_name} with email - #{user.email}"
但是,当我在 rails 控制台中运行以下命令时:
However, when I run the command below in the rails console:
UserSerializer.new(User.first).serializable_hash
我收到以下错误:
NameError(未初始化的常量 UserSerializer)
NameError (uninitialized constant UserSerializer)
我尝试了一些解决方案,但似乎都没有奏效.我需要帮助.谢谢.
I have tried a few solutions, but none seems to be working. I need some help. Thanks.
推荐答案
我是这样解决的:
退出 rails 控制台,如果你还在里面:
Exit the rails console, if you're still inside it:
exit
停止 spring Rails 应用预加载器:
Stop the spring Rails application preloader:
spring stop
再次进入开发环境rails console
:
rails console
再次运行命令:
UserSerializer.new(User.first).serializable_hash
它给出了这样的输出:
#<ActiveRecord::Relation [#<User id: 3, first_name: "Promise", last_name: "My last name", username: "myusername", password_digest: [FILTERED], email: "myemail@gmail.com", phone: "002037363", address: "my address", created_at: "2020-03-14 18:36:31", updated_at: "2020-03-14 18:36:31">]>
仅此而已.
我希望这会有所帮助
这篇关于Rails:NameError(未初始化的常量 UserSerializer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!