2013-09-25 20 views
0

我的模特兒是這樣設置的用戶<作業>課程>等級>步驟 - 用簡單的英語表示用戶參加創建分配的課程,該分配具有多個級別和多個步驟。 我正在嘗試訪問當前用戶的當前步驟,因此我可以更改數據庫中的字段。如何在rails中爲單個用戶找到模型ID和字段?

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 = @[email protected]@[email protected] 
    end 

end 

這當然是行不通的。在給出上述信息的情況下,我會如何寫@user_step?

回答

1

如果我正確理解你的情況,你不能做你想用你現有的模型做什麼。具體而言,您的Step模型有一個狀態字段是不夠的(也可能沒有意義)。如果您需要跟蹤狀態對每個用戶的每一步的基礎上,那麼你就需要它連接這兩個模型,並採用了狀態的模型,如:

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

然後,您可以修改UserStep與此型號有has_many的關係。在StepsController#show之內,您可以訪問@step.user_steps併爲您的登錄用戶選擇UserStep,此時您可以訪問該狀態。

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 ... 

你沒有必要去通過分配模型,它僅僅是一個連接,連接用戶和課程模式。

相關問題