0

I have the following code in my controller.

  def index
    @customer = Customer.find(params[:customer_id])

    @current_orders = @customer.current_orders
    @pending_orders = @customer.pending_orders
    @previous_orders = @customer.previous_orders
    @recurring_orders = @customer.recurring_orders
  end

As you see, all the instance variables(@current_orders,@pending_orders,etc) can be obtain from @customer.

What is the best way to write this code? Should I need to create these instance variable in controller or I just only used these through @customer variable in views.

1 Answer 1

2

If you reference the customer methods directly in the view you are tying the view directly to your model i.e. if for some reason you needed to change the name of the previous_orders method on customer you'd have to go through all your views and change it there, whereas with the instance variables you've used you'd only have to change it in your controllers. Using instance variables also makes your views more re-usable.

However, if you find yourself using loads of instance variables in your controllers it may be worth investigating adding another layer of abstraction in there to tidy things up.

In my opinion the example you've given is fine.

Sign up to request clarification or add additional context in comments.

Comments

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.