Leo Jweda
Leo Jweda

Reputation: 2487

Calling a Controller Action from a View... Or not?

I'll keep it short: Should I call Controller2.getByCriteria(some, criteria, here) from Controller1 then set an instance variable for the view to use, or should I call it from Controller1's view using something like = render Controller2.getByCriteria(some, criteria, here)?

Upvotes: 0

Views: 1689

Answers (2)

Swanand
Swanand

Reputation: 12426

Generally speaking, calling one controller's action from another is a design error. It either means you have common business logic, which implies the code should be in models (or maybe lib) or you have common view logic, which implies the code should be in helpers.

So in your case, I think using a helper seems apt:

module ApplicationHelper
  # ...
  def getByCriteria(some, criteria, here)
    # handle criteria here
    # Something like: 
    # render :partial => 'foo'
  end
  # ...
end

And then simply call it from the views.

If you want a full controller/view like component sharing across your application, you can use a gem called cells. It enables you to create re-usable controller and view components.

Upvotes: 2

apneadiving
apneadiving

Reputation: 115531

The proper way to do this is to declare the controller method (not controller action) as a helper.

See here.

Upvotes: 2

Related Questions