Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
I

inherited_resources

> 后端框架
Open source

Notice Inherited Resources is no longer actively maintained by the original author and has been transferred to the ActiveAdmin organization…

2.7K stars0 likes0 views
WebsiteGitHub

About

Notice Inherited Resources is no longer actively maintained by the original author and has been transferred to the ActiveAdmin organization…

Notice

Inherited Resources is no longer actively maintained by the original author and has been transferred to the ActiveAdmin organization for maintenance. New feature requests are not encouraged.

If you are not already using Inherited Resources we suggest instead using Rails' respond_with feature alongside the responders gem.

Inherited Resources

[![Version ][rubygems_badge]][rubygems] [![Github Actions ][actions_badge]][actions] [![Tidelift ][tidelift_badge]][tidelift]

Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important. It makes your controllers more powerful and cleaner at the same time.

In addition to making your controllers follow a pattern, it helps you to write better code by following fat models and skinny controllers convention. There are two screencasts available besides this README:

  • http://railscasts.com/episodes/230-inherited-resources
  • https://www.akitaonrails.com/2009/09/01/screencast-real-thin-restful-controllers-with-inherited-resources

Installation

You can let bundler install Inherited Resources by adding this line to your application's Gemfile:

ruby
gem 'inherited_resources'

And then execute:

bash
$ bundle install

Or install it yourself with:

bash
$ gem install inherited_resources

HasScope

Since Inherited Resources 1.0, has_scope is not part of its core anymore but a gem dependency. Be sure to check the documentation to see how you can use it:

  • https://github.com/heartcombo/has_scope

And it can be installed as:

bash
$ gem install has_scope

Responders

Since Inherited Resources 1.0, responders are not part of its core anymore, but is set as Inherited Resources dependency and it's used by default by InheritedResources controllers. Be sure to check the documentation to see how it will change your application:

  • https://github.com/heartcombo/responders

And it can be installed with:

bash
$ gem install responders

Using responders will set the flash message to :notice and :alert. You can change that through the following configuration value:

ruby
InheritedResources.flash_keys = [ :success, :failure ]

Notice the CollectionResponder won't work with InheritedResources, as InheritedResources hardcodes the redirect path based on the current scope (like belongs to, polymorphic associations, etc).

Basic Usage

To use Inherited Resources you just have to inherit (duh) it:

ruby
class ProjectsController < InheritedResources::Base
end

And all actions are defined and working, check it! Your projects collection (in the index action) is still available in the instance variable @projects and your project resource (all other actions) is available as @project.

The next step is to define which mime types this controller provides:

ruby
class ProjectsController < InheritedResources::Base
  respond_to :html, :xml, :json
end

You can also specify them per action:

ruby
class ProjectsController < InheritedResources::Base
  respond_to :html, :xml, :json
  respond_to :js, :only => :create
  respond_to :iphone, :except => [ :edit, :update ]
end

For each request, it first checks if the "controller/action.format" file is available (for example "projects/create.xml") and if it's not, it checks if the resource respond to :to_format (in this case, :to_xml). Otherwise returns 404.

Another option is to specify which actions the controller will inherit from the InheritedResources::Base:

ruby
class ProjectsController < InheritedResources::Base
  actions :index, :show, :new, :create
end

Or:

ruby
class ProjectsController < InheritedResources::Base
  actions :all, :except => [ :edit, :update, :destroy ]
end

In your views, you will get the following helpers:

ruby
resource        #=> @project
collection      #=> @projects
resource_class  #=> Project

As you might expect, collection (@projects instance variable) is only available on index actions.

If for some reason you cannot inherit from InheritedResources::Base, you can call inherit_resources in your controller class scope:

ruby
class AccountsController < ApplicationController
  inherit_resources
end

One reason to use the inherit_resources macro would be to ensure that your controller never responds with the html mime-type. InheritedResources::Base already responds to :html, and the respond_to macro is strictly additive. Therefore, if you want to create a controller that, for example, responds ONLY via :js, you will have to write it this way:

ruby
class AccountsController < ApplicationController
  respond_to :js
  inherit_resources
end

By default, InheritedResources::Base will inherit from ::ApplicationController. You can change this in a rails initializer:

ruby
# config/initializers/inherited_resources.rb
InheritedResources.parent_controller = 'MyController'

Overwriting defaults

Whenever you inherit from InheritedResources, several defaults are assumed. For example you can have an AccountsController for account management while the resource is a User:

ruby
class AccountsController < InheritedResources::Base
  defaults :resource_class => User, :collection_name => 'users', :instance_name => 'user'
end

In the case above, in your views you will have @users and @user variables, but the routes used will still be accounts_url and account_url. If you plan also to change the routes, you can use :route_collection_name and :route_instance_name.

Namespaced controllers work out of the box, but if you need to specify a different route prefix you can do the following:

ruby
class Administrators::PeopleController < InheritedResources::Base
  defaults :route_prefix => :admin
end

Then your named routes will be: admin_people_url, admin_person_url instead of administrators_people_url and administrators_person_url.

If you want to customize how resources are retrieved you can overwrite collection and resource methods. The first is called on index action and the second on all other actions. Let's suppose you want to add pagination to your projects collection:

ruby
class ProjectsController < InheritedResources::Base
  protected
    def collection
      get_collection_ivar || set_collection_ivar(end_of_association_chain.paginate(:page => params[:page]))
    end
end

The end_of_association_chain returns your resource after nesting all associations and scopes (more about this below).

InheritedResources also introduces another method called begin_of_association_chain. It's mostly used when you want to create resources based on the @current_user and you have urls like "account/projects". In such cases you have to do @current_user.projects.find or @current_user.projects.build in your actions.

You can deal with it just by doing:

ruby
class ProjectsController < InheritedResources::Base
  protected
    def begin_of_association_chain
      @current_user
    end
end

Overwriting actions

Let's suppose that after destroying a project you want to redirect to your root url instead of redirecting to projects url. You just have to do:

ruby
class ProjectsController < InheritedResources::Base
  def destroy
    super do |format|
      format.html { redirect_to root_url }
    end
  end
end

You are opening your action and giving the parent action a new behavior. On the other hand, I have to agree that calling super is not very readable. That's why all methods have aliases. So this is equivalent:

ruby
class ProjectsController < InheritedResources::Base
  def destroy
    destroy! do |format|
      format.html { redirect_to root_url }
    end
  end
end

Since most of the time when you change a create, update or destroy action you do so because you want to change its redirect url, a shortcut is provided. So you can do:

ruby
class ProjectsController < InheritedResources::Base
  def destroy
    destroy! { root_url }
  end
end

If you simply want to change the flash message for a particular action, you can pass the message to the parent action using the keys :notice and :alert (as you would with flash):

ruby
class ProjectsController < InheritedResources::Base
  def create
    create!(:notice => "Dude! Nice job creating that project.")
  end
end

You can still pass the block to change the redirect, as mentioned above:

ruby
class ProjectsController < InheritedResources::Base
  def create
    create!(:notice => "Dude! Nice job creating that project.") { root_url }
  end
end

Now let's suppose that before create a project you have to do something special but you don't want to create a before filter for it:

ruby
class ProjectsController < InheritedResources::Base
  def create
    @project = Project.new(params[:project])
    @project.something_special!
    create!
  end
end

Yes, it's that simple! The nice part is since you already set the instance variable @project, it will not build a project again.

Same goes for updating the project:

ruby
class ProjectsController < InheritedResources::Base
  def update
    @project = Project.find(params[:id])
    @project.something_special!
    update!
  end
end

Before we finish this topic, we should talk about one more thing: "success/failure blocks". Let's suppose that when we update our project, in case of failure, we want to redirect to the project url instead of re-rendering the edit template.

Our first attempt to do this would be:

ruby
class ProjectsController < InheritedResources::Base
  def update
    update! do |format|
      unless @project.errors.empty? # failure
        format.html { redirect_to project_url(@project) }
      end
    end
  end
end

Looks too verbose, right? We can actually do:

ruby
class ProjectsController < InheritedResources::Base
  def update
    update! do |success, failure|
      failure.html { redirect_to project_url(@project) }
    end
  end
end

Much better! So explaining everything: when you give a block which expects one argument it will be executed in both scenarios: success and failure. But if you give a block that expects two arguments, the first will be executed only in success scenarios and the second in failure scenarios. You keep everything clean and organized inside the same action.

Smart redirects

Although the syntax above is a nice shortcut, you won't need to do it frequently because (since version 1.2) Inherited Resources has smart redirects. Redirects in actions calculates depending on the existent controller methods.

Redirects in create and update actions calculates in the following order: resource_url, collection_url, parent_url (which we are going to see later), and root_url. Redirect in destroy action calculate in following order collection_url, parent_url, root_url.

Example:

ruby
class ButtonsController < InheritedResources::Base
  belongs_to :window
  actions :all, :except => [:show, :index]
end

This controller redirect to parent window after all CUD actions.

Success and failure scenarios on destroy

The destroy action can also fail, this usually happens when you have a before_destroy callback in your model which returns false. However, in order to tell InheritedResources that it really failed, you need to add errors to your model. So your before_destroy callback on the model should be something like this:

ruby
def before_destroy
  if cant_be_destroyed?
    errors.add(:base, "not allowed")
    false
  end
end

Belongs to

Finally, our Projects are going to get some Tasks. Then you create a TasksController and do:

ruby
class TasksController < InheritedResources::Base
  belongs_to :project
end

belongs_to accepts several options to be able to configure the association. For example, if you want urls like "/projects/:project_title/tasks", you can customiz

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyrails

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架