I’m designing a table on view. For instance, they have two columns are ID and name. When a user clicks to the ID column, I want the data will be sorted by ID. Similarly, if a user clicks name column, the data will be sorted by name.
My question is :
Is there any way to put this into the model (database model), hence, when user click one column, its status will be saved and the database will look at this to return record according to this status.
if not, how I put this code in view.
Please help me.
Thanks 🙂
Look at this railscasts #228 http://railscasts.com/episodes/228-sortable-table-columns
When you have functional sort columns, you then will need to save it to the db
A basic table with: user_id, page_name (or table_name), sort_column, sort_direction
Then when the user loads a page you would check against the saved settings and load them if they exist, if they don’t you can load a default.
This is the idea, I do not have time to write the code for it, but it should be fairly straight forward.
Update:
Since I had to do this at work, I will post my code.
The railscast above implements the following three functions, which allow for sorting on a column.
application_controller.rb/or specific_controller.rb
And the controller that uses it
Now, in order to remember what the user selected for the sort and to use that instead of always loading the default sortable column we need to create a table for the
user_preferencescreate a migration for the preference table like
When we search now (path -> ‘specific_controller#index?direction=asc&sort=name’) we need to save/update the user’s preference
Then we need to update our methods (sort_column/direction -> What column are we sorting/ Which direction? )