Partial
Step 1: 产生一个要调用的partial
eg: app/views/groups/_form.html.erb
touch app/views/groups/_form.html.erb
填入以下内容:
1 | <%= form_for @group do |f| -%> |
Step 2: 修改 app/views/groups/new.html.erb
修改 app/views/groups/new.html.erb,把原先重复的表单程式码“整段删掉”,改成 <%= render “form” %>
1 | <div class="col-md-4 col-md-offset-4"> |
Step 3: 修改 app/views/groups/edit.html.erb
修改 app/views/groups/edit.html.erb,把原先重复的表单程式码“整段删掉”,改成 <%= render “form” %>
1 | <div class="col-md-4 col-md-offset-4"> |
Step 4: git 存档
git add .
git commit -m “move form to partial”
ps:partial 还可以这样用
上面我们介绍了,form 可以放入 partial。这里我们要介绍 partial 还可以用在回圈上。
Step 1. 修改 app/views/groups/index.html.erb
把 @groups.each 内整段砍掉,换成 partial
1 | <div class="col-md-12"> |
然后 touch app/views/groups/_group_item.html.erb
1 | <tr> |
Step 2. git 存档
git add .
git commit -m “render partial with collection”
Helper
Step 1. 自制 render_group_description(group)
修改 app/helpers/groups_helper.rb
加入:
1 | module GroupsHelper |
然后换掉 app/views/groups/index.html.erb 与 app/views/account/groups/index.html.erb 里关于 group.description 的部分:
1 | <td><%= link_to(group.title, group_path(group)) %></td> |
Step 2 : git 储存
git add .
git commit -m “use self delimit helper”
ps:
自制的 Helper 是什么意思?
Helper 就是用 Ruby 写的“View 装饰的小方法”,你也可以自己定义
自制 Helper 都会放在 app/helpers 下
form-helper
1.checkbox 多选 与 radio button 单选
多选的例子:
<%= check_box_tag(:banana) %>
<%= label_tag(:banana, “我喜欢香蕉”) %>
<%= check_box_tag(:orange) %>
<%= label_tag(:orange, “我喜欢橘子”) %>
单选的例子:
<%= radio_button_tag(:sex, “male”) %>
<%= label_tag(:sex_male, “男”) %>
<%= radio_button_tag(:sex, “female”) %>
<%= label_tag(:sex_female, “女”) %>
2.下拉菜单:
1)自己给的选项
<%= select_tag ‘sex’, options_for_select([‘男’, ‘女’]) %>
2)在已有的信息中调取选项
<%= options_from_collection_for_select Book.all, :id, :title %>
3.填写信息框:
text_area比text_field框大
且text_field会自带默认值
text_field_tag要加默认值就要如下写:
<%= text_field_tag ‘article[title]’, ‘三体’ %>
Scope:在model中定义scope,controller中调用
1 | class Post < ApplicationRecord |