如何搜索一个对象并返回另一个相关对象
我正在尝试创建搜索表单,当用户搜索课程时,它会返回正在学习该课程的用户名列表。所以我有用户表、课程表和用户课程连接表。我想使用 元搜索 或 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
I am trying to create search form when user search for a course it returns list of user's names who are taking that course.So i have user table,course table and user-course join table.I want o use metasearch or ransack.But i wonder how i would use these in my case.Thank you in advance.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将其添加到您的课程模型中:
然后您可以像这样从课程中获取用户
You can add this to your Course model:
Then you can get the users from a course like so