【问题标题】:Suplying different names for submit buttons in forms为表单中的提交按钮提供不同的名称
【发布时间】:2016-03-05 15:17:25
【问题描述】:

我有一个适用于应用程序中所有表单的模板,但是,我想在不同的操作中为表单的提交按钮定义不同的名称(例如,当我编辑一篇文章时,我希望从提交按钮显示文本 更新文章,当我添加文章时,我希望从提交按钮显示文本添加文章)。有没有办法做到这一点,但保持呈现相同的表单模板?

<%= 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

【问题讨论】:

  • 你能显示文章控制器吗?
  • @RahulSingh 我发布了。

标签: ruby-on-rails forms


【解决方案1】:

定义一个辅助方法来检查控制器和动作名称,然后根据需要返回按钮文本

例如

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_nameaction_name 帮助器获取 Rails4 的控制器和操作名称。见here

【讨论】:

  • 不是帮助文件,ApplicationHelper 是默认的帮助文件,当您运行 rails new 命令创建新的 rails 应用程序时会生成该文件。您可以在 app/helpers 文件夹中找到它
【解决方案2】:
<%= f.submit "My Submit Text" %>

应该可以。

另外,你也应该能够通过

传递类属性
<%= f.submit "My Submit Text", class: "class class class" %>

如果您希望使用相同的表单,但有不同的操作,则需要创建一个部分_form.html.erb

在里面你需要传递“本地”变量。

在_form...你会有

<%= f.submit button_id, class: "" %> 

【讨论】:

  • 我知道如何命名按钮并提供类,但我想在按钮上为不同控制器的操作显示不同的文本(添加/编辑/显示)。如果我在 f.submit 上提供一个参数,它将显示在所有操作中。
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多