如何删除Rails控制器中的冗余代码?

时间:2012-02-25 05:30:57

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

def new
  @user = User.find(session[:this_user])
  @message = Message.new    
  @people= People.order("is_active DESC, first_name, last_name")
end

当创建操作验证失败时,我需要再次设置上述变量,创建一个如下所示的操作:

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

删除冗余代码的正确方法是什么(并干掉它)?

此外,如果验证失败,上述方法会导致表单忘记任何输入。有没有更好的方法来记住输入的任何信息?

Rails 3.07,Ruby 1.9.2

1 个答案:

答案 0 :(得分: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