2012-02-25 71 views
0
def new 
    @user = User.find(session[:this_user]) 
    @message = Message.new  
    @people= People.order("is_active DESC, first_name, last_name") 
end 

當創建行動驗證失敗,我需要重新設置上述變量,創建看起來動作,如:如何刪除Rails控制器中的多餘代碼?

def create 
    @message = Message.new(params[:message]) 
    if @message.save 
    redirect_to(messages_path, :notice => 'Message was successfully created.') 
    else 
    @user = User.find(session[:this_user]) 
    @message = Message.new  
    @people= People.order("is_active DESC, first_name, last_name") 
    render :action => "new" 
end 

什麼是去除冗餘代碼的正確方法(和DRY它)?

另外,如果驗證失敗,上述方法會導致表單忘記任何輸入。有沒有更好的方法來記錄輸入的信息?

Rails的3.07,紅寶石1.9.2

回答

2

@user = User.find(session[:this_user])before_action像這樣:

class SomeController 
    before_action :set_session_user, :only => [:new, :create] 
    def set_session_user 
    @user = User.find(session[:this_user]) 
    end 
end 

而且@people= People.order("is_active DESC, first_name, last_name")可能是scope像這樣:

class People < ActiveRecord::Base 
    scope :sorted_by_active_and_name, -> { order("is_active DESC, first_name, last_name") } 
end 
People.sorted_by_active_and_name