0

我正在尝试在用户搜索课程时创建搜索表单,它返回正在学习该课程的用户名列表。所以我有用户表、课程表和用户课程连接表。我想使用搜索 或ransack。但我想知道我将如何在我的情况下使用这些。提前谢谢你。

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
4

1 回答 1

1

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

has_many :users, :through => :user_courses

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

Course.find(1).users
于 2011-10-02T18:45:55.300 回答