如何使用 has_many :through 和 Honor :conditions 创建新记录? [英] How can I create new records with has_many :through and honor :conditions?

查看:18
本文介绍了如何使用 has_many :through 和 Honor :conditions 创建新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个课程,学生可以通过会员资格注册(例如课程和学生的 has_and_belongs_to_many 关系).一些会员资格适用于只是旁听课程(不是为了学分等)的学生,因此:

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:

  1. 新的学生记录('Joe Student')
  2. 新的会员记录(course_id = 37,student_id = (joe),observer = true)

但我得到:

ActiveRecord::AssociationTypeMismatch: Membership expected, got Array

我确定我完全不知道这是怎么回事,如果有任何见解,我将不胜感激!我也尝试使用 Membership 模型上的命名范围来执行此操作,但我似乎无法让 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

但这会创建一个成员,其中观察者字段设置为 false

But this creates a membership with the observer field set to false!

我想出的最后一个丑陋的解决方法是手动创建Membership记录:

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

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

为此创建了一张票,我会在早餐后进一步调查.

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

编辑:按照承诺,我已经进行了进一步调查,发现您是否将 :conditions 哈希更改为数组,例如:

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 存储库,其中包含示例代码和要复制的说明.

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

这篇关于如何使用 has_many :through 和 Honor :conditions 创建新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆