Search code examples
active-model-serializersruby-on-rails-5

Rails 5 and ActiveModelSerializers


I am trying to learn a bit about ActiveModelSerializers in Rails 5. I was following this tutorial and ran into some bugs:

I probably shouldn't be messing around with Rails 5 beta right?

rails -v
Rails 5.0.0.beta3

and Ruby:

ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15]

Here is my schema:

ActiveRecord::Schema.define(version: 20160303205439) do

  create_table "rental_units", force: :cascade do |t|
    t.string   "address"
    t.integer  "rooms"
    t.integer  "bathrooms"
    t.integer  "price_cents"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
  end

  add_index "rental_units", ["user_id"], name: "index_rental_units_on_user_id"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "email"
  end

end

Here is my seeds:

User.create(name: "1st user", email: "[email protected]")
User.create(name: "2nd user", email: "[email protected]")
User.create(name: "3rd user", email: "[email protected]")

RentalUnit.create(address: "1st address", rooms: 2, bathrooms: 2, price_cents: 50000, user_id:1)
RentalUnit.create(address: "2nd address", rooms: 2, bathrooms: 2, price_cents: 50000, user_id:1)
RentalUnit.create(address: "3rd address", rooms: 2, bathrooms: 2, price_cents: 50000, user_id:1)
RentalUnit.create(address: "4th address", rooms: 2, bathrooms: 2, price_cents: 50000, user_id:2)

Here is my RentalUnit Model:

class RentalUnit < ApplicationRecord
end

Here is my RentalUnitSerializer:

class RentalUnitSerializer < ActiveModel::Serializer
  attributes :id, :address, :rooms, :bathrooms, :price, :price_per_room
  belongs_to :user
end

When I try to run rails server, I get:

rs
=> Booting Puma
=> Rails 5.0.0.beta3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
/Users/Jwan/Dropbox/programming/rails/api_codeship/app/serializers/rental_unit_serializer.rb:3:in `<class:RentalUnitSerializer>': undefined method `belongs_to' for RentalUnitSerializer:Class (NoMethodError)
    from /Users/Jwan/Dropbox/programming/rails/api_codeship/app/serializers/rental_unit_serializer.rb:1:in `<top (required)>'
...

Any idea what is going on?

Anyone have any good tutorials on API design, Rails APIs, and AMS that are working?


Solution

  • You're missing has_one or has_many relationship in your RentalUnit model (and maybe User model too). Add belongs_to :user in your RentalUnit model and either has_one or has_many in your User model depending on what you want.

    I'm using Rails 5beta2 and ActiveModel Serializer and it's working fine... guessing beta3 should be only be better.