@@ -1188,7 +1188,7 @@ by passing the html5 option:
1188
1188
<%= f.input :expires_at, as: :date, html5: true % >
1189
1189
` ` `
1190
1190
1191
- # ## Using non Active Record objects
1191
+ # # Using non Active Record objects
1192
1192
1193
1193
There are few ways to build forms with objects that don't inherit from Active Record, as
1194
1194
follows :
@@ -1237,6 +1237,45 @@ class User
1237
1237
end
1238
1238
` ` `
1239
1239
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
+
1240
1279
If your object doesn't implement those methods, you must make explicit it when you are
1241
1280
building the form
1242
1281
0 commit comments