【问题标题】:Create Rails Association with different column names创建具有不同列名的 Rails 关联
【发布时间】:2016-02-13 10:47:02
【问题描述】:

我有三个模型,即通知、设备和用户。 通知有registration_ids 映射到设备的token 字段。 Devices 有 user_id 字段,该字段映射到 User 模型的 id 字段。

如何从 Notification 模型创建 as has_many_through 或 has_and_belongs_to_many 关联以提取与该通知对应的用户。

此外,我在通知类 belongs_to :device, :primary_key => 'registration_ids', :foreign_key => 'token' 中创建了这个关联,而在设备类 has_many :notifications, :primary_key => 'token', :foreign_key => 'registration_ids' 中创建了这个关联

设备类能够识别通知类,而通知类不能识别设备类

从 notification.rb 文件中查看我的代码

class Notification < Rpush::Gcm::Notification
  self.inheritance_column = nil
  belongs_to :device, :foreign_key => 'registration_ids', :primary_key => 'token'
  delegate :user, to: :device #-> notification.user.name
end

【问题讨论】:

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


    【解决方案1】:
    #app/models/notification.rb
    class Notification < ActiveRecord::Base
      belongs_to :device, foreign_key: :registration_id, primary_key: :token
      delegate :user, to: :device #-> notification.user.name
    end
    
    #app/models/device.rb
    class Device < ActiveRecord::Base
      belongs_to :user
      has_many :notifications, foreign_key: :registration_id, primary_key: :token
    end
    
    #app/models/user.rb
    class User < ActiveRecord::Base
      has_many :devices
      has_many :notifications, through: :devices
    end
    

    以上是我认为的设置方式。

    您可以拨打电话:

    @notification = Notification.find params[:id]
    
    @notification.device.user.name #-> "name" of associated "user" model
    @notification.user.name        #-> delegate to "user" model directly
    

    delegate 方法是一种规避law of demeter 问题的技巧(在“远离”父级的多个级别调用对象)。

    【讨论】:

    • 收到以下错误2.2.1 :071 &gt; Notification.last.device Notification Load (0.4ms) SELECT "rpush_notifications".* FROM "rpush_notifications" ORDER BY "rpush_notifications"."id" DESC LIMIT 1 TypeError: can't cast Array to string
    • 有趣。你有一些背景吗?我不知道你是怎么得到这个结果的——你能把请求的console日志作为屏幕截图给我看吗?
    • 好的。您的 registration_ids 专栏引起了问题。您只是想在每个单元格中存储一条数据;你要么有一个数组,要么有一个 Ruby 集合。你需要摆脱它
    • 如果您需要更多帮助,我可以聊天
    • 注册 ids 字段被配置为 Rpush gem 本身中的一个数组,我无法更改它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2021-12-26
    相关资源
    最近更新 更多