Skip to content

Commit

Permalink
Merge pull request #1839 from abinoam/improve_docs_on_non_ar
Browse files Browse the repository at this point in the history
Improve docs on Non Active Record
  • Loading branch information
nashby authored Jun 25, 2024
2 parents 62149be + 4387c28 commit 33b1c54
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1188,7 +1188,7 @@ by passing the html5 option:
<%= f.input :expires_at, as: :date, html5: true %>
```

### Using non Active Record objects
## Using non Active Record objects

There are few ways to build forms with objects that don't inherit from Active Record, as
follows:
Expand Down Expand Up @@ -1237,6 +1237,45 @@ class User
end
```

To have SimpleForm infer the attributes' types, you can provide
`#has_attribute?` and `#type_for_attribute` methods.
The later should return an object that responds to `#type`
with the attribute type. This is useful for generating
the correct input types (eg: checkboxes for booleans).

```ruby
class User < Struct.new(:id, :name, :age, :registered)
def to_model
self
end
def model_name
OpenStruct.new(param_key: "user")
end
def to_key
id
end
def persisted?
id.present?
end
def has_attribute?(attr_name)
%w(id name age registered).include?(attr_name.to_s)
end
def type_for_attribute(attr_name)
case attr_name.to_s
when "id" then OpenStruct.new(type: :integer)
when "name" then OpenStruct.new(type: :string)
when "age" then OpenStruct.new(type: :integer)
when "registered" then OpenStruct.new(type: :boolean)
end
end
end
```

If your object doesn't implement those methods, you must make explicit it when you are
building the form

Expand Down

0 comments on commit 33b1c54

Please sign in to comment.