ruby on rails-如何覆盖form_for帮助器中的类名?

我需要在表单中添加一些类名。 我正在使用Rails的form_for助手来执行此操作。 我尝试添加{ :class => 'classname' }无济于事。

如何向该Rails助手输出添加类?

James asked 2020-08-11T19:54:17Z
3个解决方案
91 votes

试试这个:

form_for @order, :html => {:class => "foo"}
Harish Shetty answered 2020-08-11T19:54:23Z
7 votes

对于Rails 4.0,以下是指南中的示例:

[HTTP://guides.Ruby on rails.org/form_helpers.HTML]

1.2表单帮助程序调用中的多个哈希

form_tag(controller: "people", action: "search", method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
Daniel answered 2020-08-11T19:54:52Z
2 votes

下面的Ruby代码

<%= form_for :article, :html => { :class => "article-form" } do |form| %>
    <p>
        <%= form.label :title %>
        <%=
        form.text_field :title,
            placeholder: "A******'s title"
        %>
    </p>
    <p>
        <%= form.label :text %>
        <%=
        form.text_field :text,
            placeholder: "A******'s content"
        %>
    </p>
    <p>
        <%= form.submit %>
    </p>
<% end %>

下面的HTML输出,

<form class="article-form" action="/articles/new" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="BRBjb0maKb5kNbGXV0wwoLeFUV6El2la/sOwweWhyN+nEIOK2Wam5Xz8PasZtpwvmiCF7yIO8Pab/OR2uoeZQA==">
    <p>
        <label for="article_title">Title</label>
        <input placeholder="A******'s title" type="text" name="article[title]" id="article_title">
    </p>
    <p>
        <label for="article_text">Text</label>
        <input placeholder="A******'s content" type="text" name="article[text]" id="article_text">
    </p>
    <p>
        <input type="submit" name="commit" value="Save Article">
    </p>
</form>
Lorem Ipsum Dolor answered 2020-08-11T19:55:28Z
translate from https://stackoverflow.com:/questions/6881645/how-do-you-override-the-class-name-in-the-form-for-helper