Developer Guide For Rails

Getting Started

Introduction

Forest instantly provides all common admin tasks such as CRUD operations, simple chart rendering, user group management, and WYSIWYG interface editor. That’s what makes Forest a quick and easy solution to get your admin interface started.

This guide assists developers in having the admin completely tailored to cater to their specific needs. We’ve developed Forest so that your admin is 100% customizable. It means that you have full control over your data, your back-end business logic and the UI.

Forest provides a very simple API-based framework to handle all parts of your admin back-end configuration. You should be good to go in no time, with virtually no learning curve.

How it works

Before you start writing a single line of code, it’s a good idea to get an overview of how Forest works.

1

The Initialization phase

Install the Forest Liana on your application

Initialization

There are three steps on the initialization phase:

2

Forest's architecture

Where the magic happens

archi

The magic of Forest lies in its architecture. Forest is divided into two main components:

  • The Forest Liana that allows Forest to communicate seamlessly with your application’s database.
  • The Forest UI (web application), accessible from any browser, that handles communication between the user and the database through your admin API.

Data Privacy

The main advantage of Forest’s architecture is that absolutely no data transits over our servers. The user accesses application data directly from the client and Forest is just deployed as a service to display and interact with the data. Read more about hosting.

With Forest, your data are transferred directly from your application to your browser while remaining invisible to our servers. See how it works.

Privacy

Security

We use a two-step authentication to connect you to both Forest’s server and your Admin API.

1

Log into your Forest account

To retrieve your UI configuration

When logging into your account, your credentials are sent to the Forest’s server which returns the UI token to authenticate your session.

2

Log into your admin API

To manage your data

Your password is sent to your Admin API which returns the data token signed by the FOREST_AUTH_SECRET you chose. Each of your requests to your Admin API are authenticated with the data token.

security

Your admin uses the UI token to make request about the UI configuration. And the data token is used to make queries on your admin API to manage your data. All our tokens are generated using the JWT standard.

Installation

If you haven’t yet, you should have Forest installed on your application. The relevant information is below. You should be set in a few minutes, no more. If you encounter any issue, feel free to drop us a line at support@forestadmin.com or using the live chat available on our homepage.

Tip: You’re using a framework based off Rails? Head over to our Github account. If support is just a matter of a couple tweaks, it’ll be listed there along with specific instructions.

# Add the liana to your application's Gemfile
gem 'forest_liana'

# Bundle it
bundle install

# Install it with the provided environment secret
rails g forest_liana:install YOUR-SUPER-SECRET-SECRET-KEY


Get Started

Glossary

Forest allows to handle even the most complex scenarios. The Smart label enables you to implement your own business logic with code, when necessary.

  • Admin API is generated by the Forest Liana to manage all your application data and business operations.
  • Collection is a set of data elements physically stored in the database displayed in tabular form (by default), with rows (i.e. records) and columns named (i.e. fields).
  • Data token is used to authenticate your requests on your Admin API.
  • Field is simply an attribute defined in your database.
  • Forest liana is a locally-installed add-on that analyzes your data model and generates the Admin API.
  • Forest UI is the web application of Forest, accessible from any browser at https://app.forestadmin.com.
  • Forest UI Schema is a schema of your data model generated by the Forest Liana.
  • FOREST_AUTH_SECRET - chosen by yourself - is an environment variable used to sign the data token.
  • FOREST_ENV_SECRET is an environment variable used to identify your project environment in Forest.
  • Relationship is a connection between two collections.
  • Segment is a subset of a collection gathering filtered records.
  • Smart Action is an action is a button that triggers server-side logic through an API call.
  • Smart Chart is a complex chart computed based on your business logic.
  • Smart Collection is a group of records gathered from different sources and implemented following your business logic.
  • Smart Field is a field that displays a computed value in your collection.
  • Smart Relationship is a field that displays a link to another collection.
  • Smart View is a custom view - specific to one collection - that displays data in any way you want.

Layout Editor

The Layout Editor is an essential tool to manage your teams permissions and optimize the admin interface of each business unit.

No coding required, you can directly configure the interface directly using the Forest Layout Editor.

Layout Editor 1

This feature is available for admin and editor roles only.

Note that if you change your admin configuration, it will be reflected on the entire team on which you are currently logged in (e.g. if you hide a collection within the "Admin" team, all users of this team will no longer see this collection).

Showing, hiding and re-ordering collections

You may want to display only relevant information to your teammates. Sometimes, sensible data shouldn’t be exposed to everyone within your company.

In the navigation sidebar containing your collections, activate the layout editor to:

  • reorder collections by drag and drop
  • hide or show collections by checking or not the box next to your collection name.

Layout Editor 2

Showing, hiding and re-ordering fields

In the same way as for collections, for the sake of clarity for operations, you can activate the layout editor to:

  • reorder fields by drag and drop
  • hide or show fields that are not relevant (e.g. id, updated_at) by checking or not the box next to your collection name.

Layout Editor 3

Collection settings

If you’ve activated the Layout Editor, you’ve certainly noticed the orange “cog” icon beside each collection name in the navigation sidebar. Clicking on this icon give you access to your collection settings.

Let’s take a closer look at each of these settings…

General

This is where you can rename your collection to make it more user-friendly, set a nice icon, change the default sorting (e.g. created_at) and more.

Layout Editor 4

Fields

In the Fields section of your collection settings, you’ll be able to:

  • change the display name of your field.
  • add a description to your field for a clearer explanation.
  • set the field in read-only mode so that users won’t be able to modify it.
  • choose from a list of widget to better display your data (google map, rich text editor, file picker, document viewer and more).

Layout Editor 5

Segments

In this section, you can create segments on your collections.

Segments are made for those who are willing to systematically visualize data according to specific sets of filters. It allows you to save your filters configuration so that you don’t have to compute the same actions every day (e.g. signup this week, pending transactions).

Layout Editor 6

If you’re looking to implement a more complex segment, you might want to take a look at Smart Segments.

Smart Actions

Smart actions are specific to your business. A smart action can be triggered from a record (e.g. user, company) or from the collection.

In the Smart Actions section of your collection settings you have 3 options:

  • display or not the action to restrict the access from your teammates
  • ask for confirmation before triggering the action
  • make the action visible on some segments only

Layout Editor 7

Smart Views

In this section you can configure your Smart Views using JS, HTML, and CSS.

To make a specific smart view as a default view, click on your collection, activate the layout editor, and drag and drop your view to the top at the top right of your screen.

Layout Editor 8

Analytics

As an admin user, KPIs are one of the most important things to follow day by day. Your customers’ growth, Monthly Recurring Revenue (MRR), Paid VS Free accounts are some common examples.

Forest can render three types of charts:

  • Single value (Number of users, MRR, …)
  • Repartition (Number of users by countries, Paid VS Free, …)
  • Time-based (Number of signups per month, …)

Ensure you’ve enabled the Edit Layout mode to add, edit or delete a chart.

Creating a Chart

Forest provides a straightforward UI to configure step-by-step the charts you want. The only information the UI needs to handle such charts is:

  • 1 collection
  • 1 aggregate function (count, sum, …)
  • 1 group by field
  • 1 time frame (day, week, month, year) option.
  • 1 or multiple filters.

Analytics 1`

What is a Smart Chart?

Sometimes, charts data are complicated and closely tied to your business. Forest allows you to code how the chart is computed.

Analytics 5`

Creating a Smart Chart

Choose “URL” as the data source when configuring your chart. Forest will make the HTTP call to this address when retrieving the chart values for the rendering.

Analytics 2`

Smart “value” Chart

The value format passed to the serializer for a Value chart must be:

<value>
1

Declare the route

config/routes.rb (add the route before the Forest engine)

namespace :forest do
  post '/stats/mrr' => 'stats#mrr'
end

# ...
# mount ForestLiana::Engine => '/forest'
2

Configure CORS

config/application.rb

We use the gem rack-cors for the CORS configuration.

class Application < Rails::Application
  # ...

  config.middleware.insert_before 0, 'Rack::Cors' do
    allow do
      origins 'app.forestadmin.com'
      resource '*', headers: :any, methods: :any
    end
  end
end
3

Create the controller

app/controllers/stats_controller.rb

class StatsController < ForestLiana::ApplicationController
  def mrr
    stat = ForestLiana::Model::Stat.new({
      value: 500000
    })

    render json: serialize_model(stat)
  end
end

Smart “repartition” Chart

The value format passed to the serializer for a Repartition chart must be:

[
  { key: <key>, value: <value> },
  { key: <key>, value: <value> },
  ...
]
1

Declare the route

config/routes.rb (add the route before the Forest engine)

namespace :forest do
  post '/stats/avg_price_per_supplier' => 'stats#avg_price_per_supplier'
end

# ...
# mount ForestLiana::Engine => '/forest'
2

Configure CORS

config/application.rb

We use the gem rack-cors for the CORS configuration.

class Application < Rails::Application
  # ...

  config.middleware.insert_before 0, 'Rack::Cors' do
    allow do
      origins 'app.forestadmin.com'
      resource '*', headers: :any, methods: :any
    end
  end
end
3

Create the controller

app/controllers/stats_controller.rb

# ForestLiana::ApplicationController takes care of the authentication for you.
class StatsController < ForestLiana::ApplicationController
  def avg_price_per_supplier
    # Your business logic here.
    value = Item
      .all
      .group(:supplier)
      .average(:price)
      .map {|supplier, avg| { key: supplier.last_name, value: avg }}

    stat = ForestLiana::Model::Stat.new({
      value: value
    })

    # The serializer_model function serializes the ForestLiana::Model::Stat
    # model to a valid JSONAPI payload.
    render json: serialize_model(stat)
  end
end

Smart “time-based” chart

The value format passed to the serializer for a Line chart must be:

[
  { label: <date key>, values: { value: <value> } },
  { label: <date key>, values: { value: <value> } },
  ...
]
1

Declare the route

config/routes.rb (add the route before the Forest engine)

namespace :forest do
  post '/stats/avg_price_per_month' => 'stats#avg_price_per_month'
end

# ...
# mount ForestLiana::Engine => '/forest'
2

Configure CORS

config/application.rb

We use the gem rack-cors for the CORS configuration.

class Application < Rails::Application
  # ...

  config.middleware.insert_before 0, 'Rack::Cors' do
    allow do
      origins 'app.forestadmin.com'
      resource '*', headers: :any, methods: :any
    end
  end
end
3

Create the controller

app/controllers/stats_controller.rb

# ForestLiana::ApplicationController takes care of the authentication for you.
class StatsController < ForestLiana::ApplicationController
  def avg_price_per_month
    # Your business logic here.
    value = Item
      .all
      .group("DATE_TRUNC('month', created_at)")
      .average(:price)
      .map do |date, avg|
        {
          label: date,
          values: { value: avg }
        }
      end
      .sort_by {|x| x[:label]}

    stat = ForestLiana::Model::Stat.new({
      value: value
    })

    # The serializer_model function serializes the ForestLiana::Model::Stat
    # model to a valid JSONAPI payload.
    render json: serialize_model(stat)
  end
end

Creating analytics per record

Forest’s dashboard is handy when it comes to monitoring the overall KPIs. But you may find the analytics module useful for a more in-depth examination of a specific company, user or any other items.

Analytics 6`

“Analytics per record” only supports Smart Charts. The parameter record_id is automatically passed in the HTTP body to access the record the user is currently seeing.

Fields

What is a field?

A field is simply an attribute defined in your database. Examples of fields: first name, gender, status, etc.

Customizing a field

Forest allows you to customize how a field appears in your admin interface. You can rename it, choosing the right widget to display (e.g. text area, image viewer, Google map), adding a description or even setting the read/write access.

Field 1`

To customize a field, go to Collection Settings -> Fields. Then select the field to start configuring it.

What is a Smart Field?

A field that displays a computed value in your collection.

Smart field

A Smart Field is a column that displays processed-on-the-fly data. It can be as simple as concatenating attributes to make them human friendly, or more complex (e.g. total of orders).

Creating a Smart Field

Try it out with 1 of these 2 examples (it only takes 3 minutes):

Example: Concatenate First and Last names

1

Create the Smart Field

lib/forest_liana/collections/user.rb

class Forest::User
  include ForestLiana::Collection

  collection :users

  field :fullname, type: 'String' do
    "#{object.firstname} #{object.lastname}"
  end
end
2

Restart your Rails server

The Smart Field will appear in your collection.

Example: Number of orders for a customer

1

Create the Smart Field

lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers

  field :number_of_orders, type: 'Number' do
    object.orders.length
  end
end
2

Restart your Rails server

The Smart Field will appear in your collection.

Updating a Smart Field

In order to update a Smart Field, you just need to write the logic to “unzip” the data. Note that the set method should always return the object it’s working on. In the example hereunder, the user is returned.

class Forest::Customer
  include ForestLiana::Collection

  collection :customers

  set_fullname = lambda do |user_updated_params, fullname_value|
    user_updated_params = fullname_value.split
    user_updated_params[:firstname] = fullname_value.first
    user_updated_params[:lastname] = fullname_value.last

    # NOTICE: Returns a hash of the updated values you want to persist
    user_updated_params
  end

  field :fullname, type: 'String', set: set_fullname do
    "#{object.firstname} #{object.lastname}"
  end
end

Searching on a Smart Field

To perform search on a Smart Field, you also need to write the logic to “unzip” the data, then the search query which is specific to your zipping. In the example hereunder, the firstname and lastname are searched separately after having been unzipped.

class Forest::Customer
  include ForestLiana::Collection

  collection :customers

  search_fullname = lambda do |query, search|
    firstname, lastname = search.split
    query.where_clause.send(:predicates)[0] << " OR (firstname = '#{firstname}' AND lastname = '#{lastname}')"

    query
  end

  field :fullname, type: 'String', search: search_fullname do
    "#{object.firstname} #{object.lastname}"
  end
end

Relationships

What is a relationship?

A relationship is a connection between two collections.

Forest supports natively all the relationships defined in your ActiveRecord models (belongsTo, hasMany, …). Check the Rails documentation to create new ones.

relationship

What is a Smart Relationship?

Sometimes, you want to create a relationship between two set of data that does not exist in your database. A concrete example could be creating a relationship between two collections available in two different databases. Creating a Smart Relationship allows you to customize with code how your collections are linked together.

Try it out with one these 2 examples (it only takes a few minutes):

Handling BelongsTo relationships

In the following example, we add the last delivery man of a customer to your Forest admin on a collection customers.

Smart relationship

1

Create the Smart Relationship

lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers

  belongs_to :last_delivery_man, reference: 'delivery_men.id' do
    object.orders.last.delivery_man # returns a "DeliveryMan" Model.
  end
end

Handling HasMany relationships

In the following example, we add the top 3 movies of an actor to your Forest admin on a collection actors.

1

Create the Smart Relationship

lib/forest_liana/collections/actor.rb

class Forest::Actor
  include ForestLiana::Collection

  collection :actors

  has_many :top_movies, type: ['string'], reference: 'movies.id'
end
2

Declare the route

config/routes.rb

namespace :forest do
  get '/actors/:actor_id/relationships/top_movies' => 'actors#top_movies'
end
3

Create the controller

app/controllers/forest/actors_controller.rb

class Forest::ActorsController < ForestLiana::ApplicationController
  def top_movies
    movies = Actor
      .find(params['actor_id'])
      .movies
      .order('imdb_rating DESC')
      .limit(3)

    render json: serialize_models(movies, include: [], count: movies.count)
  end
end
4

Restart your Rails server

The Smart Field will appear in your collection.

SmartField 1

Actions

What is an action?

An action is a button that triggers server-side logic through an API call. Without a single line of code, Forest supports natively all common actions required on an admin interface such as CRUD (Create, Read, Update, Delete), sort, search, data export.

What is a Smart Action?

Sooner or later, you will need to perform actions on your data that are specific to your business. Moderating comments, logging into a customer’s account (a.k.a impersonate) or banning a user are exactly the kind of important tasks you need to make available in order to manage your day-to-day operations.

Action

Try it out with this example (it only takes 3 minutes):

Example: Banning a user

In the following example, we add the Ban user action to your Forest admin on a collection customers.

1

Declare the action in the collection schema

lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers
  action 'Ban user'
end
2

Restart your Rails server

Your action is now visible on Forest

Action 1

3

Configure CORS

config/application.rb

We use the gem rack-cors for the CORS configuration.

class Application < Rails::Application
  # ...

  config.middleware.insert_before 0, 'Rack::Cors' do
    allow do
      origins 'app.forestadmin.com'
      resource '*', headers: :any, methods: :any
    end
  end
end
4

Declare the route

config/routes.rb (add the route before the Forest engine)

namespace :forest do
  post '/actions/ban-user' => 'customers#ban_user'
end

# ...
# mount ForestLiana::Engine => '/forest'
5

Create the controller

app/controllers/forest/customers_controller.rb

# ForestLiana::ApplicationController takes care of the authentication for you.
class Forest::CustomersController < ForestLiana::ApplicationController
  def ban_user
    # Your business logic to send an email here.
    render nothing: true, status: 204
  end
end

Handling input values

You can declare the list of fields when your action requires parameters from the Human in front of the screen. Available options for each field are:

  • Add a description that will help humans understand what value is expected.

  • Determine whether a field is to be required or not.

  • Set a default value.

  • Add a widget to provide a simple and easy-to-use way of entering value for your end-users. Five widgets are currently supported: JSON editor, rich text editor, date picker, text area, text input.

1

Add the form fields to your action

lib/forest_liana/collections/review.rb

class Forest::Review
  include  ForestLiana::Collection

  collection :reviews
  action 'Approve', fields: [{
    field: 'Comment',
    type: 'String',
    description: "Personal description",
    isRequired: true,
    defaultValue: 'I approve this comment'
    widget: 'text area'
  }]
end


Six types of field are currently supported: Boolean, Date, Number, String, File and Enum. If you choose the Enum type, you can pass the list of possible values through the enums key:

{ field: 'Country', type: 'Enum', enums: ['USA', 'CA', 'NZ'] }
2

Restart your Rails server

The action form will appear when triggering the approve action.

Action 2

HTTP request payload

Selected records ids are passed to the HTTP request when triggering the action button. The fields/values will be passed to the values attributes.

{
  "data": {
    "attributes": {
      "ids": ["4285","1343"],
      "collection_name": "reviews",
      "values": {
        "Comment":"I approve this comment"
      }
    }
  },
  "type":"reviews"
}

Customizing response

You can respond to the HTTP request with a simple status message to notify the user whether the action was successfully executed or respond in a more personalized and visible way with an html page.

To display a custom error message, you have to respond with a 400 Bad Request status code and a simple payload like this: { error: 'The error message.' }.

To display custom success message, you have to respond with a 200 OK status code and a simple payload like this: { success: 'The success message.' }.

You can also display a custom html page as a response using { html: '<h1>Congratulations!</h1><p>The comment has been successfully approved</p> ... ... ...'}.

Action 2

Downloading a file

The response of an action will be considered as a file to download if you pass the option ‘download’ to the action declaration. It’s very useful if you need actions like “Generate an invoice” or “Download PDF”.

1

Add the download option to your action

/lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers
  action 'Download file', download: true
end
2

Declare the route

config/routes.rb (add the route before the Forest engine)

namespace :forest do
  post '/actions/download-file' => 'customers#download_file'
end

# ...
# mount ForestLiana::Engine => '/forest'
3

Send the file as a response

app/controllers/forest/customers_controller.rb

class Forest::CustomersController < ForestLiana::ApplicationController
  def download_file
    data = open('https://.../file.pdf')
    send_data data.read, filename: 'myfile.pdf', type: 'application/pdf',
      disposition: 'attachment'
  end
end
4

Restart your Rails server

The action returns now a file as a response

Triggering an action from the collection

Passing the option global: true makes your Smart Action visible directly from your collection without having to select records before. For example, our “Import data” Smart Action example uses this option.

1

Add the global option to your action

/lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers
  action 'Import data', global: true
end

Action 4

Segments

What is a segment?

A Segment is a subset of a collection gathering filtered records.

Segments are made for those who are willing to systematically visualize data according to specific sets of filters. It allows you to save your filters configuration so that you don’t have to compute the same actions every day (e.g. signup this week, pending transactions).

Creating a Segment

Forest provides a straightforward UI to configure step-by-step the segments you want. The only information the UI needs to create a segment within a collection is a name and some filters.

Segment 1`

Creating a Smart Segment

Sometimes, segment are complicated and closely tied to your business. The smart segment allows you to describe the business logic behind your segment with code.

Example: Let’s say you’re working for an e-commerce website and you’re willing to see your list of VIP clients within a segmented view. A client is considered as “VIP” once he’s hit the threshold of 5 purchases onto your website. As you can see, data is coming from 2 different sources: 1) from the customers’ collection 2) from the orders’ collections. You will then be able to compute the aforementionned business logic and as described in the piece of code below:

In the following example, we add the VIP segment to your Forest admin on a collection customers.

1

Declare the segment in the collection schema

lib/forest_liana/collections/customer.rb

class Forest::Customer
  include ForestLiana::Collection

  collection :customers
  segment 'VIP' do
    { id: Customer
      .joins(:orders)
      .group('customers.id')
      .having('count(orders.id) > 5')
      .map(&:id) }
  end
end

There’s virtually no limitations to Smart Segments. The only requirement is to return a list of your collection IDs (customer IDs in this example).

2

Restart your Rails server

Your segment is now visible on Forest

Segment 2`

Collections

What is a collection?

A collection is a set of data elements physically stored in the database displayed in tabular form (by default), with rows (i.e. records) and columns named (i.e. fields). A collection has a specified number of columns, but can have any number of rows.

Forest automatically analyses your data models and instantly make your collections available in the Forest UI. It covers the majority of use cases. If needed, you can create a Smart Collection to go one step further in the customization of your admin.

What is a Smart Collection?

A Smart Collection is a Forest Collection based on your API implementation. It allows you to reconciliate fields of data coming from different or external sources in a single tabular view (by default), without having to physically store them into your database.

Fields of data could be coming from many other sources such as other B2B SaaS (e.g. Zendesk, Salesforce, Stripe), in-memory database, message broker, etc.

Creating a Smart Collection

In the following example, we create a Payment Smart Collection as follows:

Smart collection

Forest uses JSON API to serialize payload of API calls. The following example uses jsonapi-serializers Gem. You can of course use the library you want or simply serialize your data manually.

1

Create the Smart Collection

lib/forest_liana/collections/payment.rb

class Forest::Payment
  include ForestLiana::Collection

  collection :payments

  field :id, type: 'String'
  field :amount, type: 'String'
  field :currency, type: 'String'
end
2

Declare the route

config/routes.rb (BEFORE mounting the Forest Rails engine)

namespace :forest do
  resources :payments
end

Getting all records

Forest triggers the API call GET /forest/:collection_name to retrieve the list of your records.

In the following example, @payments is an array of Forest::Payment class. Let’s say:

@payments = [
  Forest::Payment.new(
    id: 1,
    amount: 1000,
    currency: 'USD'
  ),
  Forest::Payment.new(
    id: 2,
    amount: 2000,
    currency: 'EUR'
  ),
  Forest::Payment.new(
    id: 3,
    amount: 3000,
    currency: 'USD'
  ),
]
1

Implement the index method

app/controllers/forest/payments_controller.rb

require 'jsonapi-serializers'

class Forest::PaymentsController < ForestLiana::ApplicationController
  def index
    # Check above to see what @payments is.
    render json: JSONAPI::Serializer.serialize(@payments, is_collection: true)
  end
end

Getting a specific record

Forest triggers the API call GET /forest/:collection_name/:id to retrieve a specific record.

In the following example, @payment is a instance of the Forest::Payment class. Let’s take the same data sample than above:

@payments = [
  Forest::Payment.new(
    id: 1,
    amount: 1000,
    currency: 'USD'
  ),
  Forest::Payment.new(
    id: 2,
    amount: 2000,
    currency: 'EUR'
  ),
  Forest::Payment.new(
    id: 3,
    amount: 3000,
    currency: 'USD'
  ),
]
1

Implement the show method

app/controllers/forest/payments_controller.rb

You can find the record ID to retrieve in the params[:id].

  def show
    payment = @payments.select { |p| p.id.to_s == params[:id] }.first

    render json: JSONAPI::Serializer.serialize(payment)
  end

Handling BelongsTo relationships

A Smart Collection can have belongsTo relationships that point to other collections. For example, let’s say a Payment belongsTo an Order. Here’s how to configure the belongsTo relationship:

1

Create the `belongsTo` relationship

lib/forest_liana/collections/payments.rb

class Forest::Payment
  include ForestLiana::Collection

  collection :payments

  # ...
  belongs_to :order, type: 'String', reference: 'orders.id'
end
2

Link the data

app/controllers/forest/payments_controller.rb

The last step is to simply retrieve each ActiveRecord Order correctly and add it to the payments array. It should look like this:

@payments = [
  Forest::Payment.new(
    id: 1,
    amount: 1000,
    currency: 'USD',
    order: Order.find(10041)
  ),
  Forest::Payment.new(
    id: 2,
    amount: 2000,
    currency: 'EUR',
    order: Order.find(10041)
  ),
  Forest::Payment.new(
    id: 3,
    amount: 3000,
    currency: 'USD',
    order: Order.find(10041)
  ),
]

Handling HasMany relationships

A Smart Collection can have hasMany relationships that point to other collections. For example, let’s say a Payment hasMany Menu. Here’s how to configure the hasMany relationship:

1

Add the `hasMany` relationship

lib/forest_liana/collections/payments.rb

class Forest::Payment
  include ForestLiana::Collection

  collection :payments

  # ...
  has_many :menus, type: 'String', reference: 'menus.id'
end

HasMany relationships are fetched asynchronuously when needed through an API call. It means you have to catch the API call in a route and implement the logic to fetch associated records dynamically.

2

Declare the hasMany route

config/routes.rb (BEFORE mounting the Forest Rails engine)

  namespace :forest do
    get '/payments/:payment_id/menus' => 'payments#menus'
    resources :payments
  end

  # ...
  # mount ForestLiana::Engine => '/forest'
3

Configure CORS

config/application.rb

We use the gem rack-cors for the CORS configuration.

class Application < Rails::Application
  # ...

  config.middleware.insert_before 0, 'Rack::Cors' do
    allow do
      origins 'app.forestadmin.com'
      resource '*', headers: :any, methods: :any
    end
  end
end
4

Implement the hasMany method

app/controllers/payments_controller.rb

require 'jsonapi-serializers'

class Forest::PaymentsController < ForestLiana::ApplicationController

  def menus
    params[:filter] = { 'payment_id' => '2870' }
    params[:filterType] = 'and'

    getter = ForestLiana::ResourcesGetter.new(Menu, params)
    getter.perform

    render json: serialize_models(getter.records,
                                  include: getter.includes.map(&:to_s),
                                  count: getter.count)
  end
end

Searching on a Smart Collection

By default, Smart Collections are not searchable. You can pass the option is_searchable to display the search bar on the UI.

class Forest::Payment
  include ForestLiana::Collection

  collection :payments, is_searchable: true

  # ...
end

The param search is send in the HTTP body when a user enters a search in your Smart Collection.

class Forest::PaymentsController < ForestLiana::ApplicationController
  # ...

  def index
    puts params[:search]
    # ...
  end

  # ...
end

Views

What is a view?

A view is simply the way to visualize your data in the Forest UI. By default, Forest renders your data using a table view when you access multiple records and a form view to access, edit and create a specific record.

What is a Smart View?

Smart Views lets you code your view using JS, HTML, and CSS. They are taking data visualization to the next level. Ditch the table view and display your orders on a Map, your events in a Calendar, your movies, pictures and profiles in a Gallery. All of that with the easiness of Forest.

Map View 1

Creating a Smart View

Forest provides an online editor to inject your Smart View code. The editor is available on the collection settings of a collection, then in the “Smart views” tab.

The code of a Smart View is a Ember Component and simply consists of a template and a Javascript.

The template is written using Handlebars. Don’t panic it’s very simple.

Smart View 1 Collection settings -> Smart Views.

Getting your records

The records of your collection is accessible in the records property. Here’s how to iterate over them in the template section:

{{#each records as |record|}}

{{/each}}


Accessing a specific record

For each record, you will access its attributes through the forest-attributeName property. The forest- preceding the field name is required.

<p>
  {{record.forest-firstName}}
</p>

Accessing belongsTo relationships

Accessing a belongsTo relationship is exactly the same way than accessing a simple field. Forest triggers automatically an API call to retrieve the data from your Admin API only if it’s necessary. Let’s take the following schema example and display the address field of the related Customer.

Smart collection

<p>
  {{record.forest-order.forest-customer.forest-address}}
</p>

Accessing hasMany relationships

Accessing a hasMany relationship is exactly the same way than accessing a simple field. Forest triggers automatically an API call to retrieve the data from your Admin API only if it’s necessary. Let’s take the following schema example and display the available_at field of the related Menu.

Smart collection

{{#each record.forest-menus as |menu|}}
  <p>{{menu.forest-available_at}}</p>
{{/each}}

Refreshing data

In order to refresh the records on the page, trigger the fetchRecords action:

<button {{action 'fetchRecords'}}>
  Refresh data
</button>

Deleting records

The deleteRecords action lets you delete one or multiple records. A panel will automatically ask for a confirmation when a user triggers the delete action.

<button {{action 'deleteRecords' record}}>
  Delete record
</button>

Triggering a Smart Action

Here’s how to trigger your Smart Actions directly from your Smart Views:

<button {{action 'triggerSmartAction' collection 'Generate invoice' record}}>
  Generate invoice
</button>

You can pass an array or a single record.

Available properties

  • collection (Model): The current collection.
  • currentPage (Number): The current page.
  • isLoading (Boolean): Indicates if the UI is currently loading records or
  • numberOfPages (Number): The total number of available pages.
  • records (Array): Your data entries.
  • searchValue (String): The current search.

Examples

Try it out with one these 3 examples (each one taking about 10 minutes):

Example: Map view

Map View 1

1

Create the Smart View

Open the Collection settings - Smart Views

2

Implement the template

TEMPLATE

<style>
  #map_canvas { width: 100%; }
</style>

<div id="map_canvas"></div>
3

Implement the javascript

JAVASCRIPT

'use strict';
import Ember from 'ember';

export default Ember.Component.extend({
  tagName: '',
  router: Ember.inject.service('-routing'),
  map: null,
  displayMap: function () {
    var markers = [];
    $('#map_canvas').height($('.l-content').height());

    this.get('records').forEach(function (record) {
      var split = record.get('forest-geoloc').split(',');
      markers.push([split[0], split[1], record.get('id')]);
    });

    var geocoder = new window.google.maps.Geocoder();
    var latlng = new window.google.maps.LatLng(37.7869148, -122.3998675);
    var myOptions = {
      zoom: 13,
      center: latlng,
      mapTypeId: window.google.maps.MapTypeId.ROADMAP
    };

    this.map = new window.google.maps.Map(
      window.document.getElementById('map_canvas'), myOptions);

    this.addMarker(markers);
  }.observes('records.[]').on('didInsertElement'),
  addMarker: function (markers) {
    var that = this;

    markers.forEach(function (marker) {
      var lat = parseFloat(marker[0]);
      var lng = parseFloat(marker[1]);
      var myLatlng = new window.google.maps.LatLng(lat, lng);
      var recordId = marker[2];
      var record = that.get('records').findBy('id', recordId);
      var displayValue = record.get(
        that.get('collection.displayFieldWithNamespace')) ||
        record.get('forest-email') || record.get('id');

      var infowindow = new window.google.maps.InfoWindow({
        content: '<strong>' + that.get('collection.displayName') +
          '</strong><p>' + displayValue + '</p>'
      });
      var markerObj = new window.google.maps.Marker({
        position: myLatlng,
        map: that.get('map')
      });

      markerObj.addListener('click', function () {
        that.get('router')
          .transitionTo('rendering.data.collection.list.viewEdit.details',
            [that.get('collection.id'), recordId]);
      });

      markerObj.addListener('mouseover', function () {
        infowindow.open(that.get('map'), this);
      });

      markerObj.addListener('mouseout', function () {
        infowindow.close();
      });
    });
  }
});


Having done that, your Map view is now rendered on your list view.

Example: Calendar view

Calendar View 1

1

Create the Smart View

Open the Collection settings - Smart Views

2

Implement the template

TEMPLATE

<style>
  #calendar {
    padding: 20px;
    background: white;
    height:100%
  }

  #calendar .fc-toolbar.fc-header-toolbar .fc-left {
    font-size: 14px;
    font-weight: bold;
  }

  #calendar .fc-day-header {
    padding: 10px 0;
    background-color: #f7f7f7;
  }

  #calendar .fc-time {
    background-color: #f7f7f7;
  }

  #calendar .fc-event {
    background-color: #f7f7f7;
    border: 1px solid #ddd;
    color: #555;
    font-size: 14px;
  }
</style>

<div id='calendar'></div>
3

Implement the javascript

JAVASCRIPT

'use strict';
import Ember from 'ember';

export default Ember.Component.extend({
  router: Ember.inject.service('-routing'),
  loaded: false,
  loadPlugin: function() {
    var that = this;
    Ember.run.scheduleOnce('afterRender', this, function () {
      Ember.$.getScript('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js', function () {
        that.set('loaded', true);

        $('#calendar').fullCalendar({
          defaultView: 'agendaWeek',
          allDaySlot: false,
          minTime: '08:00:00',
          eventClick: function (event, jsEvent, view) {
            that.get('router').transitionTo('rendering.data.collection.list.viewEdit.details', [that.get('collection.id'), event.id]);
          }
        });
      });

      var cssLink = $('<link>');
      $('head').append(cssLink);

      cssLink.attr({
        rel:  'stylesheet',
        type: 'text/css',
        href: '//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css'
      });
    });
  }.on('init'),
  setEvent: function () {
    var events = [];
    $('#calendar').fullCalendar('removeEvents');

    this.get('records').forEach(function (chef) {
      chef.get('forest-chef_availabilities').then(function (availabilities) {
        availabilities.forEach(function (availability) {
          var event = {
            id: chef.get('id'),
            title: chef.get('forest-lastname'),
            start: availability.get('forest-available_at')
          };

          $('#calendar').fullCalendar('renderEvent', event, true);
        });
      });
    });
  }.observes('loaded', 'records.[]')
});


Having done that, your Calendar view is now rendered on your list view.

Gallery View 1

1

Create the Gallery view

Open the Collection settings - Smart Views

2

Implement the template

TEMPLATE

<style>
  .c-movies.l-table--content {
    text-align: center;
    margin-top: 15px;
    margin-bottom: 50px;
    overflow-y: auto;
  }

  .c-movies__image img {
    height: 350px;
    width: 250px;
    margin: 3px;
    border: 1px solid #bbb;
    border-radius: 3px;
		transition: all .3s ease-out;
  }

  .c-movies__image:hover {
    transform: scale(1.05);
  }
</style>

<section class="l-view__element l-view__element--table u-f-g c-movies l-table l-table--content">
  <div>
    {{#each records as |record|}}
      {{#link-to 'rendering.data.collection.list.viewEdit.details' collection.id record.id class="c-movies__image"}}
        <img class="c-movies__image" src={{record.forest-poster}}>
      {{/link-to}}
    {{/each}}
  </div>
</section>

{{table/table-footer records=records currentPage=currentPage
  fetchPage="fetchPage" currentUser=currentUser customView=customView
  updateRecordPerPage="updateRecordPerPage" collection=collection
  numberOfPages=numberOfPages fetchRecords="fetchRecords"}}
3

Implement the javascript

JAVASCRIPT

'use strict';
import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    updateRecordPerPage() {
      this.get('customView')
        .save()
        .then(() => this.sendAction('fetchRecords'));
    },
    fetchRecords(olderOrNewer) {
      this.sendAction('fetchRecords', olderOrNewer);
    }
  }
});


Having done that, your Gallery view is now rendered on your list view.

Integrations

Forest is able to leverage data from third party services by reconciliating it with your application’s data, providing it directly to your admin. All your admin actions can be performed at the same place, bringing additional intelligence to your admin and ensuring consistency.

Intercom

Configuring the Intercom integration for Forest allows you to have your user’s session data (location, browser type, …) and support conversations directly alongside the corresponding user from your application.

1

Add the Intercom integration

config/initializers/forest_liana.rb

# ...
ForestLiana.integrations = {
  intercom: {
    access_token: 'YOUR_INTERCOM_ACCESS_TOKEN',
    mapping: 'User'
  }
}
The integration needs an "extended" Intercom Access token to let the Forest liana read users and conversations.
2

Restart your Rails server

Intercom is now plugged to Forest

Intercom 1

Stripe

Configuring the Stripe integration for Forest allows you to have your user’s payments, invoices and cards alongside the corresponding user from your application. A refund action is also available out-of-the-box on the user_collection configured.

1

Add the Stripe integration

config/initializers/forest_liana.rb

# ...
ForestLiana.integrations = {
  stripe: {
    api_key: 'YOUR_STRIPE_SECRET_KEY',
    mapping: 'User.stripe_id'
  }
}
2

Restart your Rails server

Stripe is now plugged to Forest

Stripe 1

How to’s

Deploying to production

Forest makes it really simple to deploy your admin to production.

1

Create a new production environment

Click "Deploy to production"

Environment 1

2

Configure those environment variables

On your production server

Provide your FOREST_ENV_SECRET (given by Forest) and the FOREST_AUTH_SECRET (random string) in the environment variables of your production server.

3

Deploy your code

On your production server

4

Copy layout

Deploy your Forest UI configuration to your production environment

Now that you’re all set, you can duplicate the UI configuration of your development environment into your production environment to avoid having to repeat everything from the beginning. It will overwrite the default UI configuration.

Select your environment, click on “Deploy”, then “Save”. You’re now ready to use Forest on production!

Environment 2

Managing team permissions

As a user with the “admin” role (see users, roles and permissions), you can create different teams.

Easily configure the interface of your teams to:

  • Give limited access to your employees or contractors.
  • Optimize the admin interface per business unit: success, support, sales or marketing teams.

To add a new team, go to your project settings -> Teams -> + New team and start inviting your teammates.

Team permission 1

You can switch between teams by clicking on your avatar at the bottom left of your screen. Then, select the team you want to connect to. Once logged into a team, you can start customizing the interface of your team.

Team permission 1

Extending the Admin API

Forest provides instantly all the common tasks you need as an admin of your application. Sometimes, these tasks are very specific to your business. Our goal is to provide the simplest and most beautiful way to extend the default behavior automatically implemented by the Liana. That’s why the Liana only generates a standard REST API. The learning curve to extend it is next to none, meaning you can set up your own custom business logic in a matter of minutes.

1

Extend the Controller

lib/forest_liana/controllers/user_controller.rb

if ForestLiana::UserSpace.const_defined?('UserController')
  ForestLiana::UserSpace::UserController.class_eval do
    def update
      # your business logic here

      head :no_content
    end
  end
end

The previous example shows how to extend a UPDATE on a record. list, get, update, create and destroy are the methods you can override or extend.

Instead of reimplementing all the business logic of a method, you can call the default behavior by invoking your aliased method.

if ForestLiana::UserSpace.const_defined?('UserController')
  ForestLiana::UserSpace::UserController.class_eval do
    alias_method :default_update, :update

    def update
      # your business logic here

      # Continue with the default implementation
      default_update

      head :no_content
    end
  end
end

The parameters (params) passed to the method includes the collection and the ID of the record (except for the list method). A before_filter named find_resource is executed before the method. This filter is in charge of injecting to @resource the current model you are acting on.

Impersonating a user

Implementing the impersonate action allows you to login as one of your users and see exactly what they see on their screen.

The following example shows how to create an Impersonate Action on a collection named User.

1

Create the "Impersonate" action

More details can be found in the Creating an action section.

Impersonate 1

The impersonate process can be done in 2 steps:

  • POST '/actions/impersonate' returns a generated URL with a JWT token as a query param. The token contains the user ID to impersonate and the details of the admin who triggered the action.
  • GET '/actions/impersonate?token=...' verifies the JWT token, fetches the user from the database and configures the session depending on your authentication system.
2

Declare the routes

config/routes.rb

namespace :forest do
  post '/actions/impersonate' => 'actions#impersonate_token'
  get '/actions/impersonate' => 'actions#impersonate'
end
3

Create the controller

app/controllers/forest/actions_controller.rb

class Forest::CustomersController < ForestLiana::ApplicationController
  skip_before_action :authenticate_user_from_jwt, only: [:impersonate]

  # Only if you use Pretender
  impersonates :user

  def impersonate_token
    # Find the user to impersonate.
    user = User.find(params['data']['attributes']['ids'].first)

    # Build the payload of the JWT token.
    payload = {
      user_id: user.id,
      admin_email: forest_user['data']['data']['email'],
      admin_teams: forest_user['data']['data']['teams']
    }

    # Generate the token using a random secret key.
    token = JWT.encode(payload, ENV['IMPERSONATE_SECRET_KEY'], 'HS256')

    # Respond with the URL.
    render json: {
      html: "<a href='http://localhost:3000/forest/actions/impersonate?token=#{token}'>"\

              "Login as #{user.email}</a>".html_safe
    }
  end

  def impersonate
    # Decode the JWT token.
    payload = JWT.decode(params['token'], ENV['IMPERSONATE_SECRET_KEY']).first

    # Fetch the user from the database.
    user = User.find(payload['user_id'])

    # Impersonate the user using the gem Pretender
    # (https://github.com/ankane/pretender).
    impersonate_user(user)

    # Redirect to the root page of the application.
    redirect_to '/'
  end

end
2

Handle the route

Declare the route to the Express Router

var liana = require('forest-express-mongoose');

function impersonateToken(req, res, next) {

  // Find the user to impersonate
  User.findById(req.body.data.attributes.ids[0], (err, user) => {
    if (err) { return next(err); }

    // Build the payload of the JWT token
    var payload = {
      userId: user.id,
      adminEmail: req.user.data.email,
      adminTeams: req.user.data.teams,
    };

    // Generate the token using a random secret key
    var token = jwt.sign(payload, process.env.IMPERSONATE_SECRET_KEY);

    // Respond with the URL
    res.json({
      html: '<a href="http://localhost:3000/forest/actions/impersonate?token=' +
        token + '">Login as…</a>'
    });
  });
}

function impersonate(req, res, next) {
  // Decode the JWT token.
  var payload = jwt.verify(req.query.token, process.env.IMPERSONATE_SECRET_KEY);

  // Fetch the user from the database.
  User.findById(payload.userId, (err, user) => {
    if (err) { return next(err); }

    // Impersonate the user using Passport.js and redirect to the root of
    // the application.
    req.login(user, () => res.redirect('/'));
  });
}

router.post('/forest/actions/impersonate', liana.ensureAuthenticated,
  impersonateToken);

router.get('/forest/actions/impersonate', impersonate);

Impersonate 2

Importing data

Forest natively supports data creation but it’s sometimes more efficient to simply import it. This “How-to” shows a way to achieve that in your Forest admin.

1

Create the "Bulk import" with 'File' type and the 'global' option set to true

-> Smart Action - Handling input values

2

Restart your Rails server

Your action is now visible

Importing data 1

3

Declare the route

config/routes.rb

namespace :forest do
  post '/actions/bulk-import' => 'actions#bulk_import'
end
4

Create the controller

app/controllers/forest/actions_controller.rb

In the following example, we use data_uri to parse the encoded file. You should add it to your Gemfile too.

require 'data_uri'

class Forest::ActionsController < ForestLiana::ApplicationController

  def bulk_import
    uri = URI::Data.new(params.dig('data', 'attributes', 'values', 'file'))
    uri.data.force_encoding('utf-8')

    CSV.parse(uri.data).each do |row|
      # Your business logic to create your data here.
    end

    render json: { success: 'Data successfuly imported!' }
  end

end

Uploading images

Image uploading is one of the most common operations people do in their admin. There’s plenty of ways to handle it in your application. Forest supports natively the most common file attachment libraries. In case you’re not using one of them, Forest gives you the flexibility to plug your own file upload business logic.

Paperclip and CarrierWave are both well known libraries to manage file attachments in Rails. Forest supports them natively, which means you don’t need to configure anything more to upload and crop your images in Forest.

The following example shows you how to handle the update of a record image. The image field should be a string that contains the image URL. You have to configure the file picker widget on it.

Image upload 1

Having done that, your image is now rendered on your Details view. You can upload a new one when editing your record and clicking on the image. Optionally, you can also crop it.

Image upload 2

Hitting the Apply changes button will update your record with your new image encoded in base64 (RFC 2397).

Now, you have to extend the default behavior of the PUT method on your admin API to upload your image where you want. The following example shows you how to upload the image to AWS S3.

1

Override the update method

app/decorators/controllers/forest_liana/resources_controller.rb

ForestLiana::ResourcesController.class_eval do
  alias_method :default_update, :update

  # Regexp to match the RFC2397 prefix.
  REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m

  def update
    # Create the S3 client.
    s3 = AWS::S3.new(access_key_id: ENV['S3_ACCESS_KEY'],
                     secret_access_key: ENV['S3_SECRET_KEY'])
    bucket = s3.buckets[ENV['S3_BUCKET']]

    # Parse the "data" URL scheme (RFC 2397).
    data_uri_parts = raw_data.match(REGEXP) || []

    # Upload the image.
    obj = bucket.objects.create(filename(data_uri_parts),
                                base64_image(data_uri_parts),
                                opts(data_uri_parts))

    # Inject the new poster URL to the params.
    url = obj.public_url().to_s
    params['resource']['data']['attributes']['poster'] = url
    params['data']['attributes']['poster'] = url

    # Finally, call the default PUT behavior.
    default_update
  end

  private

  def raw_data
    params['data']['attributes']['poster']
  end

  def base64_image(data_uri_parts)
    Base64.decode64(data_uri_parts[2])
  end

  def extension(data_uri_parts)
    MIME::Types[data_uri_parts[1]].first.preferred_extension
  end

  def filetype(data_uri_parts)
    MIME::Types[data_uri_parts[1]].first.to_s
  end

  def filename(data_uri_parts)
    ('a'..'z').to_a.shuffle[0..7].join + ".#{extension(data_uri_parts)}"
  end

  def opts(data_uri_parts)
    {
      acl: 'public_read',
      content_type: filetype(data_uri_parts)
    }
  end

end
2

Restart your Rails server

File upload is now handled.

Image upload 3