JSONAPI relationship names and foreign-key column names in rails

232 views Asked by At

I got started following https://github.com/cerebris/peeps for writing a backend for an ember app. My trouble kind of starts that I want to use owner_id as a foreign-key column to the User table and in the resource, I want the relationship to be called owner referring to users.

# app/models/user.rb
class User < ApplicationRecord
  has_many :rentals, foreign_key: :owner_id
end
#app/models/rental.rb
class Rental < ApplicationRecord
    belongs_to :user, foreign_key: :owner_id
end
# app/resources/api/user_resource.rb
class API::UserResource < JSONAPI::Resource
  attributes :user_name, :first_name, :last_name, :email, :is_staff, :is_active, :is_superuser, :last_login, :date_joined
  has_many :rentals
end
# app/resources/api/rental_resource.rb
class API::RentalResource < JSONAPI::Resource
  attributes :title, :description, :city, :category, :image, :bedrooms

  has_one :owner
  filter :user
end

I am wondering which parameters I need to add to has_one :owner in order to signify that this should link to user resources?

1

There are 1 answers

1
Joel Blum On

I think class_name should be enough

class API::RentalResource < JSONAPI::Resource
   has_one :owner, class_name: 'User'