Trying to create a scope in rails 3 for has habtm relationship

别来无恙 提交于 2019-12-10 20:38:01

问题


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

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.

I've tried it using the scopes above, but all I'm getting back from *Section.teacher_fname_scope* is an empty array.

(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.)

Thanks for any help.


回答1:


It looks like the winning scope is:

Class Section << ActiveRecord::Base
  scope :teacher_fname_scope, lambda { |n| joins(:teachers).("teachers.first_name = ?", n) }
end

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




回答2:


This is an old question, but since I fell here, I'll leave an answer for whoever hits this question:

class Teacher < ActiveRecord::Base
  scope :by_name, ->(name) { where(first_name: name) }
end

class Section < ActiveRecord::Base
  has_and_belongs_to_many :teachers
  scope :by_teacher_name, ->(name) {
    joins(:teachers).merge(Teacher.by_name(name)) 
   }
end


来源:https://stackoverflow.com/questions/12042296/trying-to-create-a-scope-in-rails-3-for-has-habtm-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!