Ruby on rails 从Rails中的模型访问单个\u关联\u ID
在我的Rails应用程序中,我一直在使用关联收集方法“其他ID”,没有任何问题。然而,每当我试图从定义关联的模型中访问它时,Rails都不知道我在做什么。例如:Ruby on rails 从Rails中的模型访问单个\u关联\u ID,ruby-on-rails,ruby,Ruby On Rails,Ruby,在我的Rails应用程序中,我一直在使用关联收集方法“其他ID”,没有任何问题。然而,每当我试图从定义关联的模型中访问它时,Rails都不知道我在做什么。例如: class Membership < ActiveRecord::Base belongs_to :course, :touch => true belongs_to :person, :touch => true end class Day < ActiveRecord::Base
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
类成员资格true
属于:person,:touch=>true
结束
上课日true,:counter\u cache=>true
有很多:礼物,:相依=>:全部删除
有很多:人,:通过=>:礼物
销毁前:清除出席人数
def clear_出席率
mems=会员资格。其中(:课程id=>course.id,:个人id=>person\U id)
mems.update_all([“出勤率=出勤率-?”,(1/课程.天数.大小.至_f)])
结束
结束
在这种情况下,person_id始终为null。我试过self.person\u id、people.id等等,都没用。我在其他地方使用了day.person\u id,没有问题,为什么我不能在这里使用它
我正在使用Ruby 1.9.1和Rails 3.0.3。以下是我的日志中的SQL调用:
[1m[36mAREL(0.0ms)[0m[1mUPDATE“memberships”设置出勤率=出勤率-0.3333,其中(“memberships”。“course_id”=4)和(“memberships”。“person_id”(空))[0m
编辑:添加更多代码以澄清问题您真正想要的是:
def a_method
self.people.all
end
但是为了回答你的问题,
person\u ID
是正确的方法,它应该返回一个空数组,而不是空数组。我刚刚在2.3.10中尝试了这样的关联。也许你可以发布更多的代码、rails版本等。谢谢你的帮助-我自己解决了。问题是我回调的顺序。我正在尝试删除关联后,正在调用person_ID。将顺序更改为此解决了我的问题
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
上课日true,:counter\u cache=>true
有很多:礼物,:相依=>:全部删除
有很多:人,:通过=>:礼物
你想得到属于某一天的人吗?不,该方法只是一个例子。我已经更新了代码,以明确我在寻找什么。感谢您的回复-我已经按照您的要求进行了更新,包括生成的SQL。