Simple Form 使用教程
项目介绍
Simple Form 是一个为 Rails 应用程序设计的表单生成工具,旨在简化表单的创建过程。它提供了一个简洁的 DSL(领域特定语言),并且不强制任何特定的标记风格,使得开发者可以灵活地定制表单的外观和行为。
项目快速启动
安装 Simple Form
首先,将 Simple Form 添加到你的 Gemfile 中:
gem 'simple_form'
然后运行 bundle 安装:
bundle install
接下来,运行安装生成器:
rails generate simple_form:install
创建表单
在你的视图文件中,使用 Simple Form 创建表单:
<%= simple_form_for @user do |f| %>
<%= f.input :username %>
<%= f.input :password %>
<%= f.button :submit %>
<% end %>
应用案例和最佳实践
自定义输入组件
Simple Form 允许你自定义输入组件。例如,创建一个自定义的日期选择器:
# app/inputs/date_picker_input.rb
class DatePickerInput < SimpleForm::Inputs::Base
def input(wrapper_options)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.text_field(attribute_name, merged_input_options)
end
end
然后在表单中使用这个自定义输入:
<%= simple_form_for @user do |f| %>
<%= f.input :birthday, as: :date_picker %>
<% end %>
使用 Bootstrap 样式
Simple Form 可以与 Bootstrap 集成,提供美观的表单样式:
# config/initializers/simple_form_bootstrap.rb
SimpleForm.setup do |config|
config.wrappers :bootstrap, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper tag: 'div', class: 'col-sm-10' do |ba|
ba.use :input
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
end
典型生态项目
Active Storage
Simple Form 与 Active Storage 集成,可以轻松处理文件上传:
<%= simple_form_for @user do |f| %>
<%= f.input :avatar, as: :file %>
<% end %>
CarrierWave
与 CarrierWave 集成,处理文件上传:
<%= simple_form_for @user do |f| %>
<%= f.input :avatar, as: :file %>
<% end %>
Devise
Simple Form 与 Devise 集成,简化用户认证表单的创建:
<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.input :email, required: false, autofocus: true %>
<%= f.input :password, required: false %>
<%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
<%= f.button :submit, "Log in" %>
<% end %>
通过这些集成,Simple Form 可以与多个流行的 Rails 生态项目无缝协作,提供强大的表单处理能力。