Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: NameError (uninitialized constant UserSerializer)

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.

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

I have created a user_serializer for it:

class UserSerializer
  include FastJsonapi::ObjectSerializer
  attributes :first_name, :last_name, :username, :password, :email, :phone, :address
end

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: '[email protected]', password: 'mypassword', phone: '002037363', address: 'my address'
puts "Created a new user: #{user.first_name} #{user.last_name} with email - #{user.email}"

However, when I run the command below in the rails console:

UserSerializer.new(User.first).serializable_hash

I get the error below:

NameError (uninitialized constant UserSerializer)

I have tried a few solutions, but none seems to be working. I need some help. Thanks.

like image 587
Promise Preston Avatar asked Mar 15 '20 01:03

Promise Preston


1 Answers

Here's how I solved it:

Exit the rails console, if you're still inside it:

exit

Stop the spring Rails application preloader:

spring stop

Enter rails console in development environment again:

rails console

Run the command again:

UserSerializer.new(User.first).serializable_hash

It gives an output of this sort:

#<ActiveRecord::Relation [#<User id: 3, first_name: "Promise", last_name: "My last name", username: "myusername", password_digest: [FILTERED], email: "[email protected]", phone: "002037363", address: "my address", created_at: "2020-03-14 18:36:31", updated_at: "2020-03-14 18:36:31">]>

That's all.

I hope this helps

like image 160
Promise Preston Avatar answered Oct 21 '22 04:10

Promise Preston