SimpleForm雜筆記本
2014-12-05 08:50:20

使用min, max等限制input的範圍

<%= f.input :age, input_html: { min: '1' } %>

設定預設值

<%= f.input :age, input_html: { value: f.object.age || '1' } %>

將欄位變成隱藏

<%= f.input :age, as: :hidden, input_html: { value: '1' } %>

讓下拉選單沒有空白選項

<%= f.input :age, include_blank: false %>

加入非model attribute的欄位

simple form中可以使用一般的field_tag,這樣就可以使用params在一次submit中同時傳送model與非model的input值。

<%= simple_form_for @pet do |f| %>
  <%= f.input :age %>
  <%= text_field_tag 'owner_name' %>
  <%= hidden_field_tag 'pet_type', 'dog' %>
  <%= f.button :submit %>
<% end %>

上面的例子在controller接收到的params會是:

{
  pet: {
    age: "..."
  },
  owner_name: "...",
  pet_type: "dog"
}