Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two controllers with one model in Rails

I have an Order model. Customers interact with the Order model through an Orders controller. Admins interact with the Order model through a Purchases controller.

Mostly it's working, except this happens:

  1. An admin user goes to new_purchase_path
  2. The app uses the "create" action in the purchases controller, as expected
  3. The app then uses the "new" action in the order controller (not the purchases controller)
  4. App then renders the "app/purchases/new" view (not the "app/orders/new" view), despite the fact that it has switched to using the orders controller
  5. After the admin creates the order, the app then renders the "app/orders/show" view using the orders controller

What I really need to happen is this:

  1. An admin users goes to new_purchase_path
  2. The app then uses the "create" action in the purchases controller
  3. The app then uses the "new" action in the purchases controller
  4. The app then renders the "app/purchases/new" view
  5. After the admin creates the order, the app then renders the "app/purchases/show" view using the purchases controller

In app/controllers/purchases_controller.rb I have this:

  def new
    @purchase = Order.new
    respond_with @purchase
  end

If have tried variations like...

  def new
    @purchase = Order.new
    respond_with @purchase, :controller => :purchases
  end

...but nothing like that is documented for respond_with, and naturally it doesn't work. What can I do?

like image 302
steven_noble Avatar asked Dec 03 '12 11:12

steven_noble


1 Answers

A few observations:

  1. You should not use *respond_with* in the new action as it doesn't make sense for anything but HTML.
  2. You should use namespaces if you want to make some controllers for admins only. See http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing. That way you also don't need to change the name.
like image 195
Jiří Pospíšil Avatar answered Sep 28 '22 12:09

Jiří Pospíšil