我在这里使用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? %><% end %><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:
<% @post.errors.full_messages.each do |msg| %>
- <%= msg %>
<% end %><%= f.label :title %>
<%= f.text_field :title %><%= f.label :text %>
<%= f.text_area :text %><%= f.submit %>
<% end %>
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
结束
new.html.erb
最新帖子<%= form_for :post, url: posts_path do |f| %> <% if @post.errors.any? %><% end %><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:
<% @post.errors.full_messages.each do |msg| %>
- <%= msg %>
<% end %><%= f.label :title %>
<%= f.text_field :title %><%= f.label :text %>
<%= f.text_area :text %><%= f.submit %>
<% end %> <%= form_for :post do|f| %> <% end %> <%= link_to "List of Posts", posts_path %>
edit.html.erb
编辑帖子<%= render 'form' %> <%= link_to 'Back', posts_path %>
小智.. 15
如果你想在表单的提交按钮上更改文本:
<%= f.submit ( f.object.new_record? ? "Create" : "Update"), class: "btn" %>
ahnbizcad.. 7
不同的文本来自.submit
辅助方法.
它是一个表单构建器助手,而不是*-tag助手,这意味着它f
在表单块中作为参数设置或调用.但是,标记助手也会像表单构建器方法一样输出动态文本.
它引用了一些指定这个的yml文件,
en: helpers: submit: create: "Create a %{model}" update: "Confirm changes to %{model}"
使文本动态化为模型名称.
可以使用I18n gem进行自定义.
所有这些都在这里描述:http: //apidock.com/rails/ActionView/Helpers/FormBuilder/submit
不同的文本来自.submit
辅助方法.
它是一个表单构建器助手,而不是*-tag助手,这意味着它f
在表单块中作为参数设置或调用.但是,标记助手也会像表单构建器方法一样输出动态文本.
它引用了一些指定这个的yml文件,
en: helpers: submit: create: "Create a %{model}" update: "Confirm changes to %{model}"
使文本动态化为模型名称.
可以使用I18n gem进行自定义.
所有这些都在这里描述:http: //apidock.com/rails/ActionView/Helpers/FormBuilder/submit
如果你想在表单的提交按钮上更改文本:
<%= f.submit ( f.object.new_record? ? "Create" : "Update"), class: "btn" %>