1

I had a code below:

  @brand = Brand.find_by_id(params[:id])
  if @brand.nil?
    flash[:error] = Flash.record_not_found
    redirect_to admin_brands_path
  end

And another change to below:

@brand = Brand.find_by_id(params[:id])
return(flash[:error] = Flash.record_not_found and redirect_to admin_brands_path) if @brand.nil?

Which code do you think is more efficient and explain? and when you have another suggest you can share too.

Thanks in advance.

1
  • My Question is: in Rails MiniTest: I want to test a controller that get user_phone param value from HTTP X Header. how can I sent this param in my video_controller_test.rb file. like in my video_controller.rb get values as: user_phone = request.env['HTTP_X_MSISDN'].to_s Commented Dec 11, 2015 at 9:30

3 Answers 3

5

I'd do it like this:

def action
  @brand = Brand.find(params[:id])
rescue ActiveRecord::RecordNotFound
  redirect_to admin_brands_path, flash: {error: Flash.record_not_found}
end
Sign up to request clarification or add additional context in comments.

Comments

1

I feel the upper one code is better as it is easy to understand and very clean, however you can write it as following too

unless @brand = Brand.find_by_id(params[:id])
  flash[:error] = Flash.record_not_found
  redirect_to admin_brands_path
end

Comments

-1

First option is definately much better - no doubt about it. It is readable, not too much logic inside and it does only what controllers are supposed to do. Having the least lines of code really isn't a good metric.

As far as refactoring goes, I would leave it just the way it is. Maybe change #find_by_id to #find, but that's it.

1 Comment

If you just change find_by_id to find, an error will occur. Check out my answer on how to handle it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.