我有一个适用于应用中所有表单的模板,但是,我想为表单定义不同的名称'在不同的操作中提交按钮(例如,当我从提交按钮编辑我想要的文章时,显示文本更新文章,以及当我从提交中添加我想要的文章时按钮显示文本添加文章)。有没有办法做到这一点,但继续渲染相同的表单模板?
<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %>
prohibited this article from saving
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
这是ArticlesController:
class ArticlesController < ApplicationController
http_basic_authenticate_with name: "username", password: "pass", except: [:index, :show]
def index
@article = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
答案 0 :(得分:2)
定义一个辅助方法来检查控制器&amp;动作名称,然后根据需要返回按钮文本
e.g
module ApplicationHelper
def button_text
if controller.action_name == "new"
return "Add"
elsif controller.action_name == "edit"
return "Update"
else
return "Submit"
end
end
end
然后使用按钮
中定义的辅助方法<%= f.submit button_text %>
此外,您可以使用controller_name
,action_name
帮助程序从Rails4获取控制器和操作名称。见here
答案 1 :(得分:0)
<%= f.submit "My Submit Text" %>
应该有效。
另外,哟也应该能够通过
传递类别<%= f.submit "My Submit Text", class: "class class class" %>
如果您希望使用相同的表单,但有不同的操作,则需要创建部分_form.html.erb
你需要传递“本地”变量。
_form中的......你将拥有
<%= f.submit button_id, class: "" %>