【问题标题】:How to relate Her and Active Record models?如何关联 Her 和 Active Record 模型?
【发布时间】:2014-12-03 07:48:25
【问题描述】:

我有一个用于资产管理的 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" 

【问题讨论】:

  • 对于不知道her是什么的其他读者:“她”是旧的和古老的ActiveResource的替代品。链接:github.com/remiprev/her 以前没听说过,好像是个大宝石。这将有助于在问题中更多地解释这一点,我猜这导致了否决票? belongs_to 中的大写 UserResource 是故意的吗?

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord


【解决方案1】:

不确定您是否有这种可能性,但不是从您的Booking API 调用返回一个user 字段,而是将其称为user_id,然后您可能会有类似的东西:

def user
  @user ||= User.find(self.user_id)
end

如果您无法更改 API,您几乎可以做同样的事情,但命名会有点奇怪。 我使用||= 来确保您只为给定的booking 查找特定用户一次。

【讨论】:

  • 谢谢!!这行得通!只需转换为 int 以使其工作 (self.user_id.to_i)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多