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.

5 Responses to “response_for_resources_controller”

  1. Renke Grunwald Says:
    Is there a way to render a view of the parent resource without knowing the name of the controller? Like: render enclosing_resource
  2. Ian White Says:

    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.

  3. Renke Grunwald Says:
    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
  4. Ian White Says:
    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?
  5. Renke Grunwald Says:
    Oh, sorry, I guess I overlooked it ;) Well, then it is perfect, thank you!

Leave a Reply