是否可以在沒有模型的情況下使用Simple Form(by:Plataformatec)?SimpleForm不適用於(非模型形式)
https://github.com/plataformatec/simple_form
是否可以在沒有模型的情況下使用Simple Form(by:Plataformatec)?SimpleForm不適用於(非模型形式)
https://github.com/plataformatec/simple_form
您可以使用:symbol
作爲第一個參數。
<%= simple_form_for :user, url: users_path do |f| %>
<%= f.input :name, as: :string %>
...
<% end %>
它將輸出是這樣的:
<form novalidate="novalidate" class="simple_form user" action="/users" accept-charset="UTF-8" method="post">
...
<div class="input string required user_name">
<label class="string required" for="user_name">
<abbr title="required">*</abbr> Name
</label>
<input class="string required" type="text" name="user[name]" id="user_name" />
</div>
...
</form>
你也可以通過一個:symbol
而不是@object
作爲論據simple_form_for
。
<%= simple_form_for :email, :url => '/post_email' do |f| %>
<%= f.input :subject, :as => :string %>
<% end %>
這將輸出:
<form method="post" class="simple_form email" action="/post_email" accept-charset="UTF-8">
...
<input type="text" size="30" name="email[subject]" id="email_subject">
</form>
請注意以下抽獎中後衛:
:url
和每個類型input
該選項仍然使用封面下的模型。該符號應與模型名稱相匹配,它將解析爲模型並創建一個新模型並將其用於每個字段,因此表單字段中使用的屬性實際上應該存在於模型中。 –
不幸的是,simple_form依賴於使用模型。從本質上來說,像simple_form_tag和input_tag方法等價於它們的rails * _tag helper會很好。在此之前,有一個簡單的工作。
在表單中使用符號而不是類,並顯式傳遞該值以防止simple_form嘗試訪問模型屬性。
<%= simple_form_for :user, :url => '/users' do |f| %>
<%= f.text_field :name, input_html: { value: nil } %>
<% end %>
這將避免undefined method 'name' for User
錯誤。
這對我有效:<%= f.input:create_key,input_html:{value:nil},required:true,hint:「僅通過邀請,查看電子郵件中的關鍵字」%> – codenoob
如果使用集合,選擇「而不是」值「,以避免'模型'錯誤'未定義的方法'名稱' –
上述所有方法仍然會將表單數據嵌套在「用戶」或您作爲第一個參數傳遞的任何符號中。這很煩人。
要模仿simple_form的風格/優點,但刪除對象/符號依賴關係和強制數據嵌套,您可以創建一個部分。
HAML
例子:
形式視圖:
= form_tag("path/to/action", method: "POST") do
= render "path/to/partial/field", type: "string", required: true, item: "first_name"
field
部分:
- required_string = required ? "required" : ""
%div{class: "input #{type} #{required_string} #{item}"}
%label{class: "#{type} #{required_string}", for: "#{item}"}
- if required
%abbr{title: "required"}
*
= t("application.#{item}")
%input{name: "#{item}", |
placeholder: t("application.#{item}"), |
type: "#{type}", |
required: required, |
"aria-required" => "#{required}" }
也可以使用在模型外字段的表單模型內,與simple_fields_for這樣的:
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= simple_fields_for :no_model_fields do |n| %>
<%= n.input :other_field %>
<% end %>
<% end %>
這是一個簡單實用的解決方案,因爲您可以創建不同型號的字段或不使用型號
也許[我對其他問題的回答] [1]可以幫助您。 [1]:http://stackoverflow.com/a/14659270/157816 – baxang
查覈http://stackoverflow.com/questions/12146466/rails-simple-form-fields-not-related- to-the-model – Dean