How do I use sub-controllers in Ruby on Rails?
I am learning RoR, and I have a general design issue that I'm trying to work around. I want to get some input on the answer to make sure I follow some kind of best practice.
I have a page that's made up of 3 subsections, let's call them A, B, and C. Certain actions cause each of these to refresh via AJAX, so I want to have them each have a controller action that allows any of them to render individually, without the page chrome.
The way I've structured this right now is with a controller that has 4 actions: index, A, B, C
Each of A, B, and C renders its view with layout=>false so I can render just that piece via AJAX when needed. Then, you have index, which renders some extra stuff along with the view of A, B, and C.
Esentially what I want here are 3 subcontrollers, and a master controller that invokes the subcontrollers as needed. Or I think that is what I want. What I think I don't want is partial views, because there is some setup I do in the controller for each of A,B,C and I would then have to duplicate the setup code in both the controller for index and the controller for A,B,C.
The code I have in mind is something like this:
my_controller.rb:
class MyController < ApplicationController
def index
@aOutput = A
@bOutput = B
@cOutput = C
render //can use @aOutput, @bOutput, @cOutput in the view
end
def A
render :layout => false
end
def B
render :layout => false
end
def C
render :layout => false
end
end
This would enable me to now access MyController#index when I want the full page, and MyController#A, etc when I want to re-render the contents of each subsection.
The problem here is if the code is structured like this, you will run into DoubleRender errors when accessing MyController#index. What is the correct way to approach this kind of thing? Feel free to blow up any assumptions I made here, with the only requirement being a page that has three sections that can update individually as needed without r开发者_运维百科eloading the whole page.
I am not sure if I understand the problem clearly but I think here is what I think your problem is.
You want to be able to render only a view without invoking controller action entire.
This can be done by using
render :action => :action_name
You want to render some text only for ajax calls
Use
respond_to
block in order to achieve this. For example.def whatever_action .... # Your action voodoo here respond_to do |format| format.html { ... } # If it a normal HTTP request format.js {...} # If it's an ajax or JSON request end end
The design that you are proposing has basic flaws like non-adherence to some of the SOLID design principles. I strongly recommend reading a good book on basics of rails.
精彩评论