我有一个用于资产管理的API,并且正在构建一个Rails应用程序,该应用程序是使用Her的API的客户端,还可以处理身份验证。
我有一个用户活动记录模型。如何将Her模型与Active Record模型联系起来?
代码是这样的:
class Resource
include Her::Model
has_many :bookings
parse_root_in_json true, format: :active_model_serializers
end
class Booking
include Her::Model
belongs_to :User
belongs_to :Resource
parse_root_in_json true, format: :active_model_serializers
end
class User < ActiveRecord::Base
has_many :Bookings
end
当前,如果我尝试让用户进行预订,我将获得存储在预订对象中的id字段,而不是所需的用户对象。
irb(main):067:0* Resource.find(1).bookings.where(status: 'all').first.user
=> "1"
不知道是否有可能,但不要通过API调用user
返回一个字段,而是Booking
调用它user_id
,然后可能会出现以下情况:
def user
@user ||= User.find(self.user_id)
end
如果您无法更改API,则可以执行几乎相同的操作,但是命名会有些奇怪。我使用||=
来确保您只为给定的一次查找特定用户booking
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句