我有一個教程類和一個步驟類。教程有很多步驟,每一步都屬於教程。我在我的模型和路線文件中有這個設置。在教程類的show動作中,屬於該教程的所有步驟也都會加載。問題是在創建了幾個步驟後,4-6,他們將失去秩序。例如,加載的第一步是第7步,但在此之後,步驟是按順序的。我爲數據庫使用postgresql,並在gemfile中包含pg gem。 教程模式:嵌套資源無序加載
class Tutorial < ActiveRecord::Base
attr_accessible :name, :summary, :permalink
has_many :steps
validates :name, :presence => true,
:length => { :maximum => 50 },
:uniqueness => { :case_sensitive => false }
validates :summary, :presence => true,
:length => { :maximum => 2000 }
before_create :set_up_permalink
def to_param
permalink
end
private
def set_up_permalink
permalink = self.name.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
self.permalink = permalink
end
步驟模型:
class Step < ActiveRecord::Base
attr_accessible :tutorial_id, :body, :position
belongs_to :tutorial
validates :body, :presence => true
before_create :assign_position
private
def assign_position
@tutorial = self.tutorial
@position = @tutorial.steps.size
@position = @position + 1
self.position = @position
end
end
路線:
resources :tutorials do
resources :steps
end
def show
@tutorial = Tutorial.find_by_permalink(params[:id])
@steps = @tutorial.steps
@next = @steps[0]
@title = "#{@tutorial.name} - A Ruby on Rails tutorial"
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @tutorial }
end
end
教程放映視圖
<%= render :partial => @tutorial.steps %>
感謝man_reworking assign_position方法在我的待辦事項列表中。 – RobertH