找到属于课程的step_id?

时间:2012-02-24 23:53:23

标签: ruby-on-rails ruby ruby-on-rails-3 postgresql

我正在尝试在我的用户模型中编写一个函数completed_steps_for_course(course),找到用户已完成的课程的所有已完成步骤。

我的用户模型位于我希望功能生效的位置

class User < ActiveRecord::Base

  has_many :memberships, :dependent => :destroy
  has_many :groups, :through => :memberships
  has_many :enrolments, :through => :groups
  has_many :courses, :through => :enrolments
  has_many :completed_steps, :dependent => :destroy

  accepts_nested_attributes_for :memberships, :allow_destroy => true
  attr_accessible :email, :password, :password_confirmation, :memberships_attributes, :is_admin,
              :first_name, :last_name, :gender, :dob, :phone_number, :address, :city, :state, :postcode

  def started_course?(course)
    completed_steps_for_course(course).length > 0
  end

  def completed_steps_for_course(course)
    #step_in_course = Course.joins(:components => :steps).where("course_id = ?", course.id)
    #completed_steps.where("course_id = ?", course.id)
  end
end

我的课程,组件和步骤模型如下......

class Course < ActiveRecord::Base
  has_many :components, :dependent => :destroy
  has_many :steps, :through => :components, :dependent => :destroy
end

class Component < ActiveRecord::Base
  belongs_to :course
  has_many :steps, :dependent => :destroy
end

class Step < ActiveRecord::Base
  belongs_to :component
end

我想不出这个功能应该怎么样,请帮忙!我意识到这可能是一个简单的问题,但是今天的早晨咖啡显然没有帮助。

编辑我有一个表格,用于监控用户的已完成步骤,如下所示......

class CompletedStep < ActiveRecord::Base
  belongs_to :user
  belongs_to :step
  validates_presence_of :user, :step
  validates_uniqueness_of :step_id, :scope => 'user_id'
end

1 个答案:

答案 0 :(得分:1)

class User < ActiveRecord::Base
  #
  # .. other associations

  has_many :completed_steps, :dependent => :destroy do
    def for_course(course)
      joins(:step=> {:component => :course}).where("courses.id = ?", course)
    end
  end 
end

现在您可以按照以下步骤完成课程的完成步骤:

current_user.completed_steps.for_course(c1)