使用不同的列名创建Rails关联

时间:2016-02-13 10:47:02

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

我有三种型号,即通知,设备和用户。 通知的registration_ids已映射到设备的token字段。设备具有user_id字段,该字段映射到用户模型的id字段。

如何从通知模型创建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

1 个答案:

答案 0 :(得分:0)

#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问题的一种技巧(从父级调用几个级别的对象)。