2013-12-11 73 views
0

我想從用戶事件EventView.promoter_id = User.id,但它不能正常工作。這裏是我的設置(目前不正確的):has_many通過與不同的外鍵

User 
has_many :events 
has_many :promoted_event_views, :foreign_key => :promoter_id, :class_name => "EventView" 
has_many :promoted_events, :through => :event_views, :foreign_key => :promoter_id #foreign key seems to be getting ignored 

EventView 
belongs_to :event 
belongs_to :promoted_event, :class_name => "Event", :foreign_key => :event_id 
belongs_to :promoter, :foreign_key => :promoter_id, :class_name => "User" 

數據庫被設置爲:

User 
id 
..etc (irrelevant) 

Event 
id 
user_id 
...etc (irrelevant) 

EventView 
id 
user_id 
event_id 
promoter_id 
...etc (irrelevant) 

我試圖撥打:

User.all.first.promoted_events 

它的工作原理,但它給我錯誤的信息!它不涉及對EventViews(我想)的promoter_id,而是它使用USER_ID在活動

這裏發生了什麼數據庫:

User Load (0.2ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1 
Event Load (2.1ms) SELECT `events`.* FROM `events` INNER JOIN `event_views` ON `events`.`id` = `event_views`.`event_id` INNER JOIN `events` `events_promoted_events_join` ON `event_views`.`event_id` = `events_promoted_events_join`.`id` WHERE `events_promoted_events_join`.`user_id` = 1 

這是很清楚的。 user_id = 1正在導致這個問題,我該如何將其更改爲promoter_id = 1?我已經嘗試在用戶模型中設置primary_key和foreign_key,但它似乎被忽略。

ALSO:我嘗試使用finder_sql但它在Rails的棄用4

+0

我看到'belongs_to的:promoted_event,...:foreign_key =>:event_id',但我沒有看到一個'event_id'列任何地方。你確定這是你的意圖嗎? –

+0

對不起,只是編輯將它包含在事件視圖 – Rob

+0

我不知道它是否與問題有關,但在你的'EventView'中,你爲':event'指定了相同的外鍵(隱式地是'event_id' )和':promoter_event'(顯式爲'event_id')。 –

回答

0
User 
has_many :events 
has_many :promoted_event_views, :foreign_key => 'promoter_id' 
has_many :event_views 
has_many :promoted_events, :through => :event_views, :source => :promoted_event 

EventView 
belongs_to :user 
belongs_to :promoted_event, :class_name => "Event", :foreign_key => 'event_id' 
belongs_to :promoter, :foreign_key => 'promoter_id', :class_name => 'User' 
+0

nope,仍然給我相同的結果 – Rob