【问题标题】:how to search one object and return another related object如何搜索一个对象并返回另一个相关对象
【发布时间】:2011-10-02 17:38:18
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    has_many :users, :through => :user_courses
    

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

    Course.find(1).users
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多