百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

dry_crud

> 编程语言
开源

为 Rails 应用程序生成 DRY 且可特定扩展的 CRUD 控制器、视图和辅助函数

162 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

为 Rails 应用程序生成 DRY 且可特定扩展的 CRUD 控制器、视图和辅助函数

= DRY CRUD

{rdoc-image:https://github.com/codez/dry_crud/actions/workflows/build.yml/badge.svg}[https://github.com/codez/dry_crud/actions/workflows/build.yml] {rdoc-image:https://api.codeclimate.com/v1/badges/ef7488764a0d9805b37d/maintainability}[https://codeclimate.com/github/codez/dry_crud/maintainability] {rdoc-image:https://api.codeclimate.com/v1/badges/ef7488764a0d9805b37d/test_coverage}[https://codeclimate.com/github/codez/dry_crud/test_coverage]

dry_crud generates simple and extendable controllers, views and helpers that support you to DRY up the CRUD code in your Rails projects. List, search, sort, show, create, edit and destroy any model entries in just 5 minutes. Start with these artifacts and build a clean base to efficiently develop your application upon.

== Installation

Create your Rails application directly with the dry_crud application template:

rails new APP_NAME -m https://raw.github.com/codez/dry_crud/master/template.rb

If your application already exists or you prefer the DIY way, then install the Gem (gem install dry_crud), add it to your Gemfile and run the generator. You may remove the Gemfile entry again afterwards, it is not required anymore.

rails generate dry_crud [--templates haml] [--tests rspec]

By default, dry_crud generates ERB templates and Test::Unit tests. Pass the options above to generate HAML templates and/or RSpec examples instead.

We recommend to use dry_crud as a generator as described above for the best understanding and the most flexibility. When you are familiar with dry_crud, it is now also possible to use it directly as a Rails Engine. Simply add the gem to your Gemfile. You may still generate single files to adapt them:

rails generate dry_crud:file list/index.html.erb

If a dry_crud file exists in your application, it will be used, if not, the one from the engine is used. This holds for controllers, helper methods and view templates.

== Integration

To integrate dry_crud into your code, only a few additions are required:

  • For uniform CRUD functionality, just subclass your controllers from CrudController and define the +permitted_attrs+ (for StrongParameters).
  • Overwrite the +to_s+ method of your models for a human-friendly representation in captions.
  • Optionally define a +list+ scope in your models to be used in the +index+ action.
  • Optionally define a +options_list+ scope in your models to be used in select dropdowns.

From version 5.0 onwards, the major and minor version numbers will be kept in sync with Rails, and only the matching Rails version is supported.

== Background

In most Rails applications, you have some models that require basic CRUD (create, read, update, delete) functionality. There are various possibilities like Rails scaffolding, {Inherited Resources}[https://github.com/activeadmin/inherited_resources] or {Rails Admin}[https://github.com/railsadminteam/rails_admin]. Still, various parts in your application remain duplicated. While you might pull up common methods into a common superclass controller, most views still contain very similar code. And then you also have to remember the entire API of these frameworks.

Enter dry_crud.

The main idea of dry_crud is to concentrate basic functionality of your application, like CRUD actions, uniform formatting, forms and tables into specifically extendable units. dry_crud generates various foundation classes that you may browse easily and adapt freely to your application's needs. For each model, you may transparently customize arbitrary parts or just fallback to the general behavior. This applies not only for controllers, but also for view templates and helpers. There is no black box your code depends on. You lay the foundation that fits your application best.

dry_crud is a Rails generator. All code resides in your application and is open for you to inspect and to extend. You may pick whatever you consider useful or adapt what is not sufficient. Even if you do not require any CRUD functionality, you might find some helpers simplifying your work. There are no runtime dependencies to the dry_crud gem. Having said this, dry_crud does not want to provide a maximum of functionality that requires a lot of configuration, but rather a clean and lightweight foundation to build your application's requirements upon. This is why dry_crud comes as a generator and not as a Rails extension.

dry_crud does not depend on any other gems, but easily allows you to integrate them in order to unify the behavior of your CRUD controllers. You might even use the gems mentioned above to adapt your generated CrudController base class. All classes come with thorough tests that provide you with a solid foundation for implementing your own adaptions.

A basic CSS gets you started with your application's layout. For advanced needs, dry_crud supports the styles and classes used in {Bootstrap}[http://getbootstrap.com]. As the views are generated into your application code, you are free to change the styling to your needs.

If you find yourself adapting the same parts of dry_crud for your applications over and over, please feel free to {fork me on Github}[http://github.com/codez/dry_crud].

See the Examples section for some use cases and the Generated Files section below for details on the single classes and templates.

== Examples

=== Controller with CRUD functionality

Say you want to manage a +Person+ model. Overwrite the +to_s+ method of your model for a human-friendly representation used in page titles.

app/models/person.rb: class Person def to_s [lastname, firstname].compact.join(' ') end end

Then create the following controller. The +permitted_attrs+ define the attribute parameters allowed when creating or updating a model entry (see {Strong Parameters}[http://api.rubyonrails.org/classes/ActionController/StrongParameters.html]).

app/controllers/people_controller.rb: class PeopleController _list partial in app/views/people/_list.html.erb to customize this:

This only displays these four attributes in the table. All other templates, as well as the main index view, fallback to the ones in app/views/crud.

==== Adapt general behavior

Next, let's adapt a part of the general behavior used in all CRUD controllers. As an example, we include pagination with kaminari[https://github.com/kaminari/kaminari] in all our overview tables:

In app/controllers/list_controller.rb, change the list_entries method to def list_entries model_scope.page(params[:page]) end

In app/views/list/index.html.erb, add the following line for the pagination links:

And we are done. All our controllers inheriting from ListController, including above +PeopleController+, now have paginated index views. Because our customization for the people table is in the separate _list partial, no further modifications are required.

==== Special formatting for selected attributes

Sometimes, the default formatting provided by +format_attr+ will not be sufficient. We have a boolean column +female+ in our model (which is quite a legacy nowadays!), but we would like to display 'male' or 'female' for it (instead of 'no' or 'yes', which is a bit cryptic). Just define a method in your view helper starting with format_, followed by the class and attribute name:

In app/helpers/people.rb: def format_person_female(person) person.female ? 'female' : 'male' end

Should you have attributes with the same name for multiple models that you want to be formatted the same way, you may define a helper method format_{attr} for these attributes.

By the way: The method +f+ in FormatHelper uniformly formats arbitrary values according to their class.

==== Sorting and filtering the index list

The entries listed on the index page are automatically sortable by each displayed database column. To apply a default sorting order, define a +list+ scope in your model:

In app/models/person.rb: scope :list, -> { order('lastname, firstname').includes(:city) }

Alternatively, set the following class attribute in the controller:

In app/controllers/people_controller.rb: self.default_sort = 'lastname, firstname'

When you display computed values in your list table, you may define sort mappings to enable sorting of these columns:

In app/controllers/people_controller.rb: self.sort_mappings = { age: 'birthday', city_id: 'cities.name' }

There is also a simple search functionality (based on SQL LIKE queries) implemented in Crud::Searchable. Define an array of columns in your controller's +search_columns+ class variable to make the entries searchable by these fields:

In app/controllers/people_controller.rb: self.search_columns = [:firstname, :lastname]

If you have search columns defined, a search box will be displayed in the index view that enables filtering of the displayed entries.

=== Standard Tables and Forms

dry_crud provides two builder classes for update/create forms and tables for displaying entries of one model. They may be used all over your application to DRY up the form and table code. Normally, they are used with the corresponding methods from TableHelper and FormHelper. In there are generic helper methods (+plain_table+ and +plain_form+/+standard_form+) and slightly enhanced ones for views of subclasses of CrudController (+crud_table+ and +crud_form+).

==== Tables

The following code defines a table with some attribute columns for a list of same-type entries. Columns get a header corresponding to the attribute name:

If entries is empty, a basic 'No entries found' message is rendered instead of the table.

To render custom columns, use the +col+ method with an appropriate block:

For views of subclasses of ListController, you can directly use the +crud_table+ helper method, where you do not have to pass the @people list explicitly and actions are added automatically.

==== Forms

Forms work very similar. In the most simple case, you just have to specify which attributes of a model to create input fields for, and you get a complete form with error messages, labeled input fields according the column types and a save button:

Of course, custom input fields may be defined as well:

   female
   male

Even +belongs_to+ associations are automatically rendered with a select field. By default, entries returned from the +options_list+ scope of the associated model are used as options (if defined, all otherwise). To customize this, either define an instance variable with the same name as the association in your controller, or pass a list option:

Yes, it's bad practice to use finder logic in your views! Define the variable @hometowns in your controller instead (as shown in the example above), and you do not even have to specify the list option.

Optionally, +has_and_belongs_to_many+ and +has_many+ associations can be rendered with a multi-select field. Similar to a +belongs_to+ association, all entries from the associated model are used, but can be overwritten using the list option:

And yes again, the same advice for where to put finder logic applies here as well.

Note: +has_and_belongs_to_many+ and +has_many+ associations are not automatically rendered in a form, you have to explicitly include these attributes. You might also want to stylize the multi-select widget with a JavaScript library of your choice.

=== Nested Resources

In case you define nested resources, your CrudController subclass should know. Listing and creating entries as well as displaying links for these resources is dependent on the nesting hierarchy. This is how you declare the namespaces and parent resources in your controller:

self.nesting = :my_namspace, ParentResource

This declaration is for a controller nested in +parent_resources+ within a +:my_namespace+ scope. +ParentResource+ is the corresponding +ActiveRecord+ model. The request param +:parent_resource_id+ is used to load the parent entry, which in turn is used to filter the entries listed and created in

Issues· 1 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言