开发者

Instance variable vs method calling in Controller

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜