2016-02-13 55 views
1

我有三个模型,即通知,设备和用户。 通知有registration_ids,它被映射到设备的token字段。设备有user_id字段,该字段映射到用户模型的id字段。使用不同的列名创建导轨协会

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

回答

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问题一招(调用从父对象几个层次“离开”)。

+0

得到以下错误'2.2.1:。071> Notification.last.device 通知负载(0.4ms)SELECT “rpush_notifications” * FROM “rpush_notifications” ORDER BY “rpush_notifications”, “ID” DESC LIMIT 1 类型错误:不能投射数组到字符串 ' – vipin8169

+0

有趣。你有一些背景吗?我不知道你是如何得到这个结果的 - 你能否以屏幕截图的形式显示请求的'console'日志? –

+0

这里是来自控制台的screeshot - http://postimg.org/image/r9wrr3vhx/ – vipin8169