我如何能创造新的纪录与的has_many:通过与荣誉:条件是什么?荣誉、纪录、条件、has_many

2023-09-09 22:08:19 作者:神经质先生"

让我们说我有一个课程,学生可以通过会员注册(课程与学生例如,一个has_and_belongs_to_many relationsip)。有些成员是学生谁是刚刚观察类(不适用于信用卡等),因此:

Let's say I have a Course in which Students can enroll via a Membership (e.g. a has_and_belongs_to_many relationsip of Courses and Students). Some memberships are for students who are just observing the class (not for credit, etc.), so:

class Course < ActiveRecord::Base
  has_many :memberships

  has_many :students,
           :through => :memberships

  has_many :observers,
           :through => :memberships,
           :source => :student,
           :conditions => { :memberships => { :observer => true }}
end

下面就是伟大工程:

observers = Course.find(37).observers

下面就是不起作用:

new_observer = Course.find(37).observers.build(:name => 'Joe Student')

我本来以为,人们可以使用该协会建立新的记录,以及将产生的:

I would have thought that one could build new records using the association and that would have generated:

在一个新的学生记录(乔学生') 在一个新的会员记录(COURSE_ID = 37,STUDENT_ID =(JOE),观察者= TRUE)

而是我得到:

ActiveRecord::AssociationTypeMismatch: Membership expected, got Array

我敢说,我完全糊涂了有关如何以及将AP preciate任何见解!我也试着用对会员制模式命名范围做到这一点,但我似乎无法得到的has_many使用范围,该协会。

I'm sure I'm totally confused about how this and would appreciate any insights! I've also tried to do this with named scopes on the Membership model, but I can't seem to get has_many to use a scope in the association.

非常感谢您的帮助可能的!

Thanks so much for any help possible!

推荐答案

我相信你已经遇到了Rails的错误。我想同样的事情在我的盒(2.3.4),它给了我同样的错误,这似乎不正确的。此外,我也试过围绕工作:

I believe that you have encountered a Rails bug. I tried the same thing on my box (2.3.4) and it gives me the same error which doesn't seem right at all. Additionally I also tried the work around of:

course = Course.first
course.observers << Student.create(:name => "Joe Student")
course.save

但是,这将创建一个与观测场集中的成员为错误!

最后一个丑陋的解决办法,我想出了手动创建成员记载:

The final ugly workaround I came up with was creating the Membershiprecord manually:

Membership.create!(:course => Course.first, :student => Student.first, :observer => true)

我有created为此一票,我会在早餐后进一步调查。

I've created a ticket for this and I'll be investigating further after breakfast.

修改:我已经按照承诺,进一步研究发现,如果你改变你的:条件散到数组,如:

EDIT: I have, as promised, investigated further and found if you change your :conditions Hash to an Array such as:

:conditions => ["memberships.observer = ?", true]

它按预期工作。我也有一个 GitHub的资源库,提供例如code和指令重复。

It works as intended. I also have a github repository with example code and instructions to duplicate.

 
精彩推荐
图片推荐