如何搜索一个对象并返回另一个相关对象

时间:2011-10-02 17:38:18

标签: ruby-on-rails ruby-on-rails-3 meta-search

我正在尝试在用户搜索课程时创建搜索表单,它返回正在参加该课程的用户姓名列表。所以我有用户表,课程表和用户课程连接表。我想要使用{{3 }}或metasearch。但我想知道如何在我的情况下使用这些。请提前感谢。

create_table "users", :force => true do |t|
  t.string   "firstname"
  t.string   "email"
  t.string   "encrypted_password",   :limit => 128, :default => "", :null => false
  t.string   "password_salt",                       :default => "", :null => false
end


create_table "courses", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "school_id",  :null => false
end

create_table "user_courses", :force => true do |t|
  t.integer "user_id",   :null => false
  t.integer "course_id", :null => false
  t.boolean "active",    :null => false
end

class User < ActiveRecord::Base
  has_many :user_courses
  has_many :courses, :through => :user_courses
  has_many :active_courses, :through => :user_courses, :source => :course, :conditions => {'user_courses.active' => true}
  has_many :taken_courses, :through => :user_courses, :source => :course, :conditions => {'user_courses.active' => false}
end

class UserCourse < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
end

class Course < ActiveRecord::Base
  validates_presence_of :name
  has_many :user_courses
  belongs_to :school
end

1 个答案:

答案 0 :(得分:1)

您可以将其添加到课程模型中:

has_many :users, :through => :user_courses

然后你就可以从这样的课程中获得用户

Course.find(1).users