ahn*_*cad 5 forms ruby-on-rails submit button
我在这里使用ruby on rails指南 http://guides.rubyonrails.org/getting_started.html
在5.13节:我在提交按钮上显示两个不同的文本值,但在"_form"部分文件中,代码完全相同.Rails似乎会以某种方式自动更改文本值.在两个视图中实现此目的的代码在哪里:new.html.erb和edit.html.erb.
(我的问题是手动控制文本,而是,我试图了解这种自动行为来自Rails的位置.)
_partial
<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Run Code Online (Sandbox Code Playgroud)
posts_controller
class PostsController < ApplicationController
def new
@posts = Post.all
@post = Post.new
end
def show
@post = Post.find(params[:id])
end
def index
@posts = Post.all
end
# called by the posts_path function
def create
@post = Post.new(post_params)
if @post.save
# Using redirect_to creates a new request.
redirect_to @post
else
# Using render sends back the @post variable's data!
# i.e. uses same request.
render 'new'
end
end
# Can only have one instance of render of redirect_to.
#render text: params[:post].inspect
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text))
redirect_to @post
else
render 'edit'
end
end
def edit
@post = Post.find(params[:id])
end
# For SQL injection prevention.
private
def post_params
params.require(:post).permit(:title, :text)
end
Run Code Online (Sandbox Code Playgroud)
结束
new.html.erb
<%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= form_for :post do|f| %>
<% end %>
<%= link_to "List of Posts", posts_path %>
Run Code Online (Sandbox Code Playgroud)
edit.html.erb
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
Run Code Online (Sandbox Code Playgroud)
小智 15
如果你想在表单的提交按钮上更改文本:
<%= f.submit ( f.object.new_record? ? "Create" : "Update"), class: "btn" %>
Run Code Online (Sandbox Code Playgroud)
不同的文本来自.submit辅助方法.
它是一个表单构建器助手,而不是*-tag助手,这意味着它f在表单块中作为参数设置或调用.但是,标记助手也会像表单构建器方法一样输出动态文本.
它引用了一些指定这个的yml文件,
en:
helpers:
submit:
create: "Create a %{model}"
update: "Confirm changes to %{model}"
Run Code Online (Sandbox Code Playgroud)
使文本动态化为模型名称.
可以使用I18n gem进行自定义.
所有这些都在这里描述:http: //apidock.com/rails/ActionView/Helpers/FormBuilder/submit
| 归档时间: |
|
| 查看次数: |
6482 次 |
| 最近记录: |