试图打造轨道3的范围进行了HABTM关系 [英] Trying to create a scope in rails 3 for has habtm relationship
问题描述
我试图做一个有效记录的一个基本的搜索,但我有因为has_and_belongs_to_many关系的麻烦。下面是记录和范围,我创建的。
I'm trying to do a basic search on an active record but am having trouble because of the has_and_belongs_to_many relationship. Below are the records and scopes I've created.
Class Section << ActiveRecord::Base
has_and_belongs_to_many :teachers
attr_accessible :department, :class_size
scope :department_scope, lambda { |dept| where("department = ?", dept) }
scope :teacher_fname_scope, lambda { |n| joins(:teachers) & Teacher.has_first_name(n) }
end
Class Teacher << ActiveRecord::Base
has_and_belongs_to_many :sections
attr_accessible :first_name, :last_name
scope :has_first_name, lambda { |fname| where("first_name = ?", fname) }
end
在Rails 3.2我创建一个基本的搜索我的部分型号。假设我想做一个搜索所有部分与给定first_name的一个老师。
In Rails 3.2 I'm creating a basic search for my Sections model. Suppose I want to do a search for all Sections with a Teacher with a given first_name.
我已经试过了使用上述范围,但所有我从* Section.teacher_fname_scope *取回是一个空数组。
I've tried it using the scopes above, but all I'm getting back from *Section.teacher_fname_scope* is an empty array.
(实际上,我有多个字段,让用户也搜索类似部门和class_size科领域,所以我可能会创建多个范围,并最终把它们结合在一起,比如通过同时上面的搜索受限于部门和class_size,但我的理解是这两个范围正交所以这并不重要的问题上面。)
(I'm actually going to have multiple fields, to let the user also search on Section fields like department and class_size so I'll probably create multiple scopes and ultimately chain them together, e.g. the above search by also limited by department and class_size, but my understanding is the scopes are orthogonal so this won't matter to the question above.)
感谢您的帮助。
推荐答案
它看起来像中奖范围是:
It looks like the winning scope is:
Class Section << ActiveRecord::Base
scope :teacher_fname_scope, lambda { |n| joins(:teachers).("teachers.first_name = ?", n) }
end
这是有道理的,但我不明白为什么原来没有工作,给瑞恩·贝茨在的 http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast
This makes sense but I don't see why the original didn't work, given what Ryan Bates talks about in http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast
这篇关于试图打造轨道3的范围进行了HABTM关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!