2011-01-23 55 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版本等。