B Seven
B Seven

Reputation: 45943

How to remove redundant code in Rails controller?

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

When the create action fails validation, I need to set up the above variables again, creating an action that looks like:

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

end

What is the proper way to remove redundant code (and DRY it)?

Also, the above approach causes the form to forget any input if the validation fails. Is there a better way to do it so that it remembers any information entered?

Rails 3.07, Ruby 1.9.2

Upvotes: 0

Views: 124

Answers (1)

j_mcnally
j_mcnally

Reputation: 6958

Put @user = User.find(session[:this_user]) in a before_action like so:

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

And @people= People.order("is_active DESC, first_name, last_name") could be a scope like so:

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

Upvotes: 2

Related Questions