response_for_resources_controller
November 20th, 2007
If you're using response_for, then you might want to grab response_for_resources_controller
It simply replaces the default action modules with ones that use the response_for idiom.
This means that you can override what an action does without overriding how it responds. For example, I want a standard REST controller, that sets a protected attribute, user, on create.
class PostsController < ApplicationController
resources_controller_for :posts
def create
self.resource = new_resource
resource.user = current_user
save_resource
end # the standard response_for :create is used
end
If you don't know what response_for does, it lets you declaratively set the respond_to of an action. For example: if you want to override some aspect of the response, here I just want to change the flash message on successful create:
class LoginsController < ApplicationController
resources_controller_for :logins
response_for :create do |format|
format.html { flash[:notice = "You have logged in" } if resource_saved?
end
end
miscellany
I added save_resource and resource_saved? to rc, as a way of sharing the result of the save outside the scope of the action. Previously I've done this with valid?, but realised that this might hit the database unnecessarily in some circumstances. You can use either idiom.
December 11th, 2007 at 03:42 PM Is there a way to render a view of the parent resource without knowing the name of the controller? Like: render enclosing_resource
December 11th, 2007 at 05:23 PM
Renke: you could avail yourself of enclosing_resource_name
render :template => "#{enclosing_resource_name.pluralize}/#{action_name}" (but the resource will not be the enclosing resource when that view is rendered)Or, check out inherit_views which allows you to setup inheritance for your views, and you can set arbitrary inheritance paths.
December 27th, 2007 at 07:05 PM In the first place: Thank you for that advice! Might there be a way to limit the created methods, say I do not want to make a CRUD-controller. So that you do something like: resources_controller_for :resource, :except => :edit, :delete I am not sure if that is a good idea, but I think sometime it might be helpful! Best regards, Renke
December 27th, 2007 at 10:52 PM Hi Renke, Yes, you can do this already in resources_controller
resources_controller_for :resources, :only => :index resources_controller_for :resources :except => [:create, :new]if you don't have this functionality, maybe you're using a older version?December 28th, 2007 at 06:04 PM Oh, sorry, I guess I overlooked it ;) Well, then it is perfect, thank you!