简体   繁体   English

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

[英]Create Rails Association with different column names

I have three models namely, Notifications, Devices and Users. 我有三种模型,即通知,设备和用户。 Notification has registration_ids which is mapped to the token field of devices. 通知具有registration_ids ,它映射到设备的token字段。 Devices has user_id field which is mapped to the id field of User model. 设备具有映射到用户模型的id字段的user_id字段。

How do I create as has_many_through or has_and_belongs_to_many association from Notification model to extract the user corresponding to that notification. 如何从Notification模型中创建具有has_many_through或has_and_belongs_to_many关联,以提取与该通知相对应的用户。

Moreover, I created this association in Notifications class belongs_to :device, :primary_key => 'registration_ids', :foreign_key => 'token' and this one in device class has_many :notifications, :primary_key => 'token', :foreign_key => 'registration_ids' 此外,我在Notifications类的belongs_to :device, :primary_key => 'registration_ids', :foreign_key => 'token'创建了这个关联属属belongs_to :device, :primary_key => 'registration_ids', :foreign_key => 'token'而在设备类中的此has_many :notifications, :primary_key => 'token', :foreign_key => 'registration_ids'

device class is able to recognize the notification class, while notification class is not able to recognize the device class 设备类别能够识别通知类别,而通知类别无法识别设备类别

Following the piece of my code from notification.rb file 按照我的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
#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

The above is how I would perceive it to be set up. 以上是我对它的设置的看法。

You'll be able to call: 您将可以致电:

@notification = Notification.find params[:id]

@notification.device.user.name #-> "name" of associated "user" model
@notification.user.name        #-> delegate to "user" model directly

The delegate method is a trick to circumvent the law of demeter issue (calling an object several levels "away" from the parent). delegate方法是一种规避放law of demeter问题的技巧(将对象称为“离父对象数个级别”的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM