【问题标题】:JSONAPI relationship names and foreign-key column names in railsRails 中的 JSONAPI 关系名称和外键列名称
【发布时间】:2021-08-17 16:03:18
【问题描述】:

我开始关注 https://github.com/cerebris/peeps 为 ember 应用程序编写后端。我的麻烦开始于我想使用owner_id 作为User 表的外键列,在资源中,我希望将关系称为owner,指的是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

我想知道我需要将哪些参数添加到has_one :owner 以表明它应该链接到用户资源?

【问题讨论】:

  • 为什么不直接将关联改为belongs_to :owner, class_name: 'User'

标签: ruby-on-rails json-api jsonapi-resources


【解决方案1】:

我觉得class_name应该够了

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

【讨论】:

  • 这样我得到Internal Server Error: Can't join 'Rental' to association named 'owner'; perhaps you misspelled it?
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
相关资源
最近更新 更多