0

我的模型设置为用户<作业>课程>级别>步骤-用简单的英语,用户参加创建分配的课程,该分配有许多级别和许多步骤。我正在尝试访问当前用户的当前步骤,因此我可以更改数据库中的字段。

class User < ActiveRecord::Base
  has_many :assignments, dependent: :destroy
  has_many :courses, through: :assignments
end

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

class Course < ActiveRecord::Base
  has_many :assignments
  has_many :users, through: :assignments
  has_many :levels
  accepts_nested_attributes_for :levels, allow_destroy: true
end

class Level < ActiveRecord::Base
  belongs_to :course
  has_many :steps
  accepts_nested_attributes_for :steps, allow_destroy: true
end

class Step < ActiveRecord::Base
  belongs_to :level
end

我的步骤模型有一个名为“状态”的字段,它确定用户的步骤是否已完成 - 我正在尝试为当前用户访问步骤的“状态”,因此我可以更改它或将其显示为我请求。为了做到这一点,我需要在我的控制器中获取用户的当前步骤(不仅仅是当前步骤,因为这会改变每个人的值)。

class StepsController < ApplicationController   
    before_filter :authenticate_user!

    def show
        @course = Course.find(params[:course_id])
        @level = Level.find(params[:level_id])
        @step = Step.find(params[:id])
        @step_list = @level.steps
            // the above all work fine up to this point
        @assignment = Assignment.find(params["something goes here"])
        @user_step = @assignment.@course.@level.@step
    end

end

这当然行不通。鉴于上述信息,我将如何编写@user_step?

4

2 回答 2

1

如果我正确理解你的情况,你不能用你目前拥有的模型做你想做的事。Step具体来说,您的模型只有一个状态字段是不够的(而且可能没有真正意义) 。如果您需要跟踪每个用户每一步的状态,那么您需要一个模型来连接这两个模型并合并一个状态,例如:

def UserStep < ActiveRecord::Base
  belongs_to :users
  belongs_to :steps
end

然后,您可以修改UserStephas_many此模型建立关系。在StepsController#show中,您可以访问@step.user_stepsUserStep为您的登录用户选择 ,此时您可以访问该状态。

于 2013-09-26T00:27:06.937 回答
0

你有一个 current_user 吗?那么你可能应该能够做到这一点:

course = current_user.courses.find(params[:course_id])
level = course.levels.find(params[:level_id])
step = level.steps.find(params[:id])

# Do something with the step ...

您不必通过作业模型,它只是一个连接用户和课程的连接模型。

于 2013-09-26T06:25:58.867 回答