nicholas79171
nicholas79171

Reputation: 1273

How can I allow users to choose the columns shown in Rails?

I have a model named Employee that has over a dozen fields making it impractical to display all fields at once. I would like to allow users to choose which columns are displayed by using either a multiple select box or a list of checkboxes, the result of which would ideally be stored in memory, not in the model since nothing will be saved long term, and be accessible for a loop to display the appropriate columns.

A sample of the view might be like so:

<% for employee in @employees %>
  <tr>
    <% for col in col_list %>
      <td><%= employee.col %></td>
    <% end %>
  </tr>
<% end %>

where col_list is the list of columns selected by the user.

Upvotes: 2

Views: 140

Answers (2)

max
max

Reputation: 102036

A better approach might be to output all the columns server side and do the filtering with javascript in the client. There are several libraries for this such as jQuery Datatables.

You can combine this with a preferences model which is persisted to the session or Redis instead of the main RDBMS if you want to remember the user prefs.

(Yes, you can use models for objects not stored in the DB. It gives you all the rails awesomeness of validations, form and param binding etc.)

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176402

As it is described, there is nothing particularly complicated in this feature.

If you have the users logged in somewhere, you can store a serialized list of columns somewhere in a preference for the user. The list of columns should probably be sanitized to avoid showing private columns.

If the user is not logged in, or you want a less persistent approach, simply store the list in a cookie.

If the list is not set (aka the cookie is empty), set it to a default or just render a default list of attributes.

Upvotes: 1

Related Questions