Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is there a better way to do this? im kinda ending up having a lot of if statements. Any hints would be great!

if params[:custom_url] || params[:user_id]
    if !params[:user_id].blank?
      @user = User.find(params[:user_id]).first
      @url = @user.custom_url
    else
      @url = params[:custom_url]
      @user = User.where(:custom_url => @url).first
    end
end
share|improve this question
1  
instead of !params[:user_id].blank?, you can write params[:user_id].present? which reads more nicely. –  rubiii Aug 11 '12 at 12:23

2 Answers 2

I typically chain scopes together like this:

Model:

def self.by_user_and_url(user_id, custom_url)
  by_user(user_id).by_custom_url(custom_url)
end

def self.by_user(user_id)
  user_id ? where(user_id: user_id) : scoped
end

def self.by_custom_url(custom_url)
  custom_url ? where(custom_url: custom_url) : scoped
end

Controller:

if params[:custom_url].present? || params[:user_id].present?
  @user = User.by_user_and_url(params[:user_id], params[:custom_url]).first
end

I'm not sure why you had two instance variables. The url can be pulled from the @user instance variable if you need it in your view.

share|improve this answer

Not a big fan of case..when:

@user = User.find_first(params[:user_id]) if params[:user_id]
@user ||= User.find_by_custom_url(@url)

@url = params[:custom_url] || @user.custom_url
share|improve this answer
2  
At line 2, @url is going to be nil, so there's no sense using it as a param. –  Pavling Aug 11 '12 at 20:32
    
Line 1, wouldn't it be better to use if params[:user_id].present? –  deiga Feb 11 '13 at 19:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.