我一直在我的Rails应用程序中使用association_collection方法"other_ids“,没有任何问题。但是,每当我试图从定义关联的模型中访问它时,Rails都不知道我在说什么。例如:
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“设置考勤=出勤- 0.3333333333333333,其中("memberships"."course_id”= 4) AND ("memberships"."person_id“IN (NULL))[0m
编辑:添加更多代码以澄清问题
发布于 2011-01-24 02:35:20
谢谢你的帮助,这是我自己想出来的。问题出在我回调的顺序上。在删除关联后,我尝试呼叫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发布于 2011-01-23 16:07:29
你真正想要的是:
def a_method
self.people.all
end但是为了回答您的问题,person_ids是正确的方法,它应该返回一个空数组,而不是nil。我刚刚在2.3.10中尝试了一个类似的关联。也许你可以发布更多的代码,rails版本,等等。
https://stackoverflow.com/questions/4772777
复制相似问题