[英]Submit a parameter via form_for that isn't an attribute on the model instance?
我有一個相對簡單的問題。 我有一個form_for
效果很好,我想傳遞一個不屬於用戶 model 或任何關聯的 model 的隨機參數(例如,它不應依賴於accepts_nested_attributes_for
)。
當我嘗試將其添加到表單時:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<h2>Sign up</h2
<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%= f.label :foo %>
<%= f.text_field :foo %>
<%= f.submit "Sign up" %>
<%= render "devise/shared/links" %>
<% end %>
加載視圖時出現此錯誤:
undefined method `foo' for #<User id: nil, first_name: nil, last_name: nil, admin: nil, last_seen_at: nil, time_zone: nil, phone: nil, temp_role: nil, created_at: nil, updated_at: nil, email: "">
我明白為什么會發生錯誤; 因為用戶 model 沒有 foo 屬性。
但我仍然想將foo
變量傳遞給 controller。最好的方法是什么(假設有辦法)?
有一種方法可以在不編輯 model 的情況下執行此操作,如果此參數實際上不是 model 的一部分,則可能會很方便。
您可以像這樣在form_for
中添加普通標簽:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<h2>Sign up</h2
<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%= label_tag :foo %>
<%= text_field_tag :foo %>
<%= f.submit "Sign up" %>
<%= render "devise/shared/links" %>
<% end %>
在這種情況下,參數foo
將在user
hash 之外,因此params
將類似於
{"user"=> ["first_name"=> "Bob"], "foo"=>"bar"...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.