首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Rails中的模型访问singular_association_ids

从Rails中的模型访问singular_association_ids
EN

Stack Overflow用户
提问于 2011-01-23 15:38:08
回答 2查看 117关注 0票数 0

我一直在我的Rails应用程序中使用association_collection方法"other_ids“,没有任何问题。但是,每当我试图从定义关联的模型中访问它时,Rails都不知道我在说什么。例如:

代码语言:javascript
复制
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

编辑:添加更多代码以澄清问题

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-24 02:35:20

谢谢你的帮助,这是我自己想出来的。问题出在我回调的顺序上。在删除关联后,我尝试呼叫person_ids。把顺序改成这个解决了我的问题。

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2011-01-23 16:07:29

你真正想要的是:

代码语言:javascript
复制
def a_method
  self.people.all
end

但是为了回答您的问题,person_ids是正确的方法,它应该返回一个空数组,而不是nil。我刚刚在2.3.10中尝试了一个类似的关联。也许你可以发布更多的代码,rails版本,等等。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4772777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档