2011-01-23 75 views
0

我一直在使用整個Rails應用程序中的association_collection方法「other_ids」,沒有任何問題。然而,無論何時我嘗試從定義關聯的模型中訪問它,Rails都不知道我在做什麼。例如:從Rails中的模型訪問singular_association_ids

class Membership < ActiveRecord::Base 
    belongs_to :course, :touch => true 
    belongs_to :person, :touch => true 
end 

class Day < ActiveRecord::Base 
    belongs_to :course, :touch => true, :counter_cache => true 
    has_many :presents, :dependent => :delete_all 
    has_many :people, :through => :presents 

    before_destroy :clear_attendance 

    def clear_attendance 
     mems = Membership.where(:course_id => course.id, :person_id => person_ids)             
     mems.update_all(["attendance = attendance - ?", (1/course.days.size.to_f)]) 
    end 
end 

在這種情況下,person_ids始終爲空。我試過self.person_ids,people.ids等等,一切都沒有。我在其他地方使用過day.person_ids而沒有問題,所以爲什麼我不能在這裏使用它?

我使用Ruby 1.9.1和Rails 3.0.3。以下是我的日誌中的SQL調用:

[1m [36mAREL(0.0ms)[0m [1mUPDATE「memberships」SET attendance = attendance - 0.3333333333333333 WHERE(「memberships」。「course_id」= 4)AND(「membershiphips 」。 「PERSON_ID」 IN(NULL))[0米

編輯:添加更多的代碼,以澄清問題

+0

你想讓人們知道:屬於一天嗎? – EnabrenTane 2011-01-23 07:50:14

+0

不,這種方法只是一個例子。我已經更新了代碼以明確我正在尋找的內容。 – Tyler 2011-01-23 17:14:55

回答

0

感謝您的幫助 - 我自己想出了它。問題在於我的回調順序。在關聯被刪除後,我試圖調用person_ids。改變這個命令解決了我的問題。

class Day < ActiveRecord::Base 
    before_destroy :clear_attendance 

    belongs_to :course, :touch => true, :counter_cache => true 
    has_many :presents, :dependent => :delete_all 
    has_many :people, :through => :presents 
1

你真的想有什麼是:

def a_method 
    self.people.all 
end 

但是,爲了回答你的問題,person_ids是正確的方法,它應該返回一個空數組,而不是零。我剛剛在2.3.10中嘗試過這樣的關聯。也許你可以發佈一些更多的代碼,rails版本等。