SimpleForm without for (non model form) SimpleForm without for (non model form) ruby-on-rails ruby-on-rails

SimpleForm without for (non model form)


You can use :symbol as the first argument.

<%= simple_form_for :user, url: users_path do |f| %>  <%= f.input :name, as: :string %>  ...<% end %>

It will output something like this:

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


Unfortunately simple_form relies on using a model. Essentially it would be nice to have something like simple_form_tag and input_tag methods equivalent to their rails *_tag helpers. Until then, there's an easy work around.

Use a symbol instead of the class in the form and pass the value explicitly to prevent simple_form from trying to access the model properties.

<%= simple_form_for :user, :url => '/users' do |f| %>  <%= f.text_field :name, input_html: { value: nil } %><% end %>

This will avoid the undefined method 'name' for User error.


You can also use fields outside the model within a form model, with simple_fields_for like this:

<%= simple_form_for @user do |f| %>  <%= f.input :name %>  <%= simple_fields_for :no_model_fields do |n| %>    <%= n.input :other_field %>  <% end %><% end %>

This is simple and practical solution, because you can create different kind of fields from different models or without using models