Skip to content

Commit 33b1c54

Browse files
authored
Merge pull request #1839 from abinoam/improve_docs_on_non_ar
Improve docs on Non Active Record
2 parents 62149be + 4387c28 commit 33b1c54

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

README.md

+40-1
Original file line numberDiff line numberDiff line change
@@ -1188,7 +1188,7 @@ by passing the html5 option:
11881188
<%= f.input :expires_at, as: :date, html5: true %>
11891189
```
11901190

1191-
### Using non Active Record objects
1191+
## Using non Active Record objects
11921192

11931193
There are few ways to build forms with objects that don't inherit from Active Record, as
11941194
follows:
@@ -1237,6 +1237,45 @@ class User
12371237
end
12381238
```
12391239

1240+
To have SimpleForm infer the attributes' types, you can provide
1241+
`#has_attribute?` and `#type_for_attribute` methods.
1242+
The later should return an object that responds to `#type`
1243+
with the attribute type. This is useful for generating
1244+
the correct input types (eg: checkboxes for booleans).
1245+
1246+
```ruby
1247+
class User < Struct.new(:id, :name, :age, :registered)
1248+
def to_model
1249+
self
1250+
end
1251+
1252+
def model_name
1253+
OpenStruct.new(param_key: "user")
1254+
end
1255+
1256+
def to_key
1257+
id
1258+
end
1259+
1260+
def persisted?
1261+
id.present?
1262+
end
1263+
1264+
def has_attribute?(attr_name)
1265+
%w(id name age registered).include?(attr_name.to_s)
1266+
end
1267+
1268+
def type_for_attribute(attr_name)
1269+
case attr_name.to_s
1270+
when "id" then OpenStruct.new(type: :integer)
1271+
when "name" then OpenStruct.new(type: :string)
1272+
when "age" then OpenStruct.new(type: :integer)
1273+
when "registered" then OpenStruct.new(type: :boolean)
1274+
end
1275+
end
1276+
end
1277+
```
1278+
12401279
If your object doesn't implement those methods, you must make explicit it when you are
12411280
building the form
12421281

0 commit comments

Comments
 (0)