Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve docs on Non Active Record #1839

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1187,7 +1187,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 @@ -1236,6 +1236,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