2016-02-13 20 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