Editable Datagrid for Ruby on Rails Built with dhtmlxGrid

| Comments (54)

NOTE: This tutorial is for RoR 2. If you’re using RoR 3, please see additional details here.

We’ve also posted an updated tutorial for Ruby on Rails 4.

This tutorial will show you how to display tabular data in Ruby on Rails with dhtmlxGrid Standard Edition, which is available under GNU GPL. At the end, we will have a datagrid with in-line editing, sorting, and filtering, which loads its data from the server and saves it back to the database using Ruby on Rails.

To illustrate, we will create a table of users. This is a very common task for nearly any web application. Working with RoR, we could use scaffolds, but they don’t work so well for navigation on large sets of data. Besides, dhtmlxGrid has client-side editing and filtering functionality, which can greatly simplify things. This is how our final grid will look:

dhtmlxGrid and RoR Example: Editable Ajax Grid

dhtmlxGrid and RoR Example: Editable Ajax Grid


Setting the Environment

To start, we create DB migration for a table of users. It will have 3 fields for storing First Name, Last Name and Phone Number. We will also create a couple of test records to see how the grid will look.

ruby script/generate migration create_users

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
            t.string :first_name
            t.string :last_name
            t.string :phone
           
      t.timestamps
    end
    User.create(
        :first_name => "John",
        :last_name => "Smit",
        :phone => "555 198 877")
    User.create(
        :first_name => "Stanislav",
        :last_name => "Wolski",
        :phone => "456 456 454")    
  end

  def self.down
    drop_table :users
  end
end

rake db:migrate

Additionally we need to create a model and controller for our demo:

ruby script/generate model user
ruby script/generate controller admin

Now we are ready to start building the main part of the users table.

Loading Empty Grid

As I said, on the client side we will be using dhtmlxGrid. The Standard Edition can be downloaded here.

When you download the grid package, unzip it and copy the dhtmlxGrid/codebase and dhtmlxDataProcessor/codebase folders to the /public/javascript/ folder of your demo application. The dhtmlxGrid package contains lots of examples and supporting materials which are not needed in the application, so we are taking only the code we need.

After that we can add our first action in /app/controllers/admin_controller.rb:

class AdminController < ApplicationController
    def view
    end
end

We also create the first view – the file /app/views/admin/view.rhtml:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <script src="/javascripts/codebase/dhtmlxcommon.js" type="text/javascript" charset="utf-8"></script>
        <script src="/javascripts/codebase/dhtmlxgrid.js" type="text/javascript" charset="utf-8"></script>
        <script src="/javascripts/codebase/dhtmlxgridcell.js" type="text/javascript" charset="utf-8"></script>
       
        <link rel="stylesheet" href="/javascripts/codebase/dhtmlxgrid.css" type="text/css" media="screen" charset="utf-8">
        <link rel="stylesheet" href="/javascripts/codebase/skins/dhtmlxgrid_dhx_skyblue.css" type="text/css" media="screen" charset="utf-8">
    </head>
    <body>
        <div id="grid_here" style="width:600px; height:400px;">
        </div>
        <script type="text/javascript" charset="utf-8">
            var grid = new dhtmlXGridObject("grid_here");
            grid.setImagePath("/javascripts/codebase/imgs/");
            grid.setHeader("First name, Last name, Phone");
            grid.setInitWidths("100,100,*");
            grid.setSkin("dhx_skyblue");
            grid.init();
        </script>
        <input type="button" value="Add" onclick="grid.addRow(grid.uid(),'new user')">
        <input type="button" value="Delete" onclick="grid.deleteSelectedRows()">
    </body>
</html>

As you can see, this view doesn’t contain any active logic, it just loads js and css files and initializes JavaScript grid on the page.

Some important points to note:

  • setImagePath points to codebase/imgs from the dhtmlxGrid package.
  • setHeader defines the structure of the grid, so the client-side grid will have columns to show data from our Users table (columns First Name, Last Name, and Phone Number).
  • setInitWidths command defines the widths of columns, and * as the width for the last column enables auto-size for this column.

 
Add new route in the routes.rb:

map.resource :admin,
    :collection => {
      :view       => :get,
      :dbaction => :get,
      :data        => :get
    }

Now, if you go to http://localhost:3000/admin/view, you will see something similar to the following:

dhtmlxGrid and RoR Example: Empty Grid

dhtmlxGrid and RoR Example: Empty Grid

This will be the structure of our table of users.

Filling Grid with Data

dhtmlxGrid can load its content from an XML data source, so loading data into the grid is pretty simple due to the ability of Rails to generate XML feeds.

We will add one more action in /app/controller/admin_controller.rb:

class AdminController < ApplicationController
    def view
    end
    def data
        @users = User.all()
    end
end

And also let’s create one more view. The file is /app/views/admin/data.rxml:

xml.instruct! :xml, :version=>"1.0"

xml.tag!("rows") do
    @users.each do |user|
        xml.tag!("row",{ "id" => user.id }) do
            xml.tag!("cell", user.first_name)
            xml.tag!("cell", user.last_name)
            xml.tag!("cell", user.phone)
        end
    end
end

The template has a .rxml extension because we will generate XML, not HTML. Inside the template we are outputting data from the Users table as XML.

Our last step will be to add one more line to the code in the /app/views/admin/view.rhtml file:

        <script type="text/javascript" charset="utf-8">
            var grid = new dhtmlXGridObject("grid_here");
            grid.setImagePath("/javascripts/codebase/imgs/");
            grid.setHeader("First name, Last name, Phone");
            grid.setInitWidths("100,100,*");
            grid.setSkin("dhx_skyblue");
            grid.init();
            grid.load("/admin/data"); //added !
        </script>

With this additional line, we’ve defined that the grid will load data from the XML feed we’ve just created.

Now our page at http://localhost:3000/admin/view is showing that the grid correctly loaded the initial set of data.

dhtmlxGrid and RoR Example: Load Records in Grid

dhtmlxGrid and RoR Example: Load Records in Grid

Saving Grid Data

Showing data in the grid was pretty easy, but it is useless without the ability to edit and save changes done by users when they edit grid records in the browser.

Fortunately, dhtmlxGrid has a special extension, DataProcessor, which is available in the grid package and allows you to synchronize client-side data changes with the server-side database. To “switch on” the DataProcessor extension, we need to implement one more action. In /app/controllers/admin_controller.rb:

class AdminController < ApplicationController
    def view
    end
    def data
        @users = User.all()
    end
    def dbaction
        #called for all db actions
        first_name = params["c0"]
        last_name    = params["c1"]
        phone            = params["c2"]
       
        @mode = params["!nativeeditor_status"]
       
        @id = params["gr_id"]
        case @mode
            when "inserted"
                user = User.new
                user.first_name = first_name
                user.last_name = last_name
                user.phone = phone
                user.save!
               
                @tid = user.id
            when "deleted"
                user=User.find(@id)
                user.destroy
               
                @tid = @id
            when "updated"
                user=User.find(@id)
                user.first_name = first_name
                user.last_name = last_name
                user.phone = phone
                user.save!
               
                @tid = @id
        end
    end
end

We’ve got quite a big piece of code compared to our previous steps.

In our new dbaction method, we are doing the following:

  • Getting parameters from the incoming request. We are using c0, c1 … cN parameters, which are related to the columns of grid: c0 – the first column, c1 – the second column, etc.
  • Getting the type of operation: inserted, updated or deleted
  • Getting the ID of a grid row

 
When we have all the above info, the code executes logic for each operation: it adds a new user for “inserted”; it deletes and updates user info for “deleted” and “inserted” operations.

In addition to this action we need to create one more XML view, which will be a response to an update operation. In the file /app/views/admin/dbaction.rxml:

xml.instruct! :xml, :version=>"1.0"

xml.tag!("data") do
    xml.tag!("action",{ "type" => @mode, "sid" => @id, "tid" => @tid })
end

The “tid” parameter in the above code provides a new ID value, which can (and will) be changed after the insert operation. The grid creates a temporary ID for a new record, which needs to be changed with an actual ID after saving the grid data.

The server-side part is ready, so we only need to point our grid to the dbaction feed.
In /app/views/admin/view.rhtml we add:

<script src="/javascripts/codebase/dhtmlxdataprocessor.js" type="text/javascript" charset="utf-8"></script>
        ...
        <script type="text/javascript" charset="utf-8">
            var grid = new dhtmlXGridObject("grid_here");
            grid.setImagePath("/javascripts/codebase/imgs/");
            grid.setHeader("First name, Last name, Phone");
            grid.setInitWidths("100,100,*");
            grid.setSkin("dhx_skyblue");
            grid.init();
            grid.load("/admin/data");
           
            dp = new dataProcessor("/admin/dbaction/");
            dp.init(grid);
        </script>
        <input type="button" value="Add" onclick="grid.addRow(grid.uid(),'new user')">
        <input type="button" value="Delete" onclick="grid.deleteSelectedRows()">

With this code, we are:

  • Including one more file, to activate DataProcessor
  • Adding two JS lines to initialize DataProcessor, pointing it to the dbaction feed
  • Adding buttons to add and delete rows in the grid

 
Now, if you try the application on http://localhost:3000/admin/view, you will see that all changes, as well as added and deleted records, are stored in the DB automatically.

The way to make “inserted” function to work is:
1. Click button. A new row with some default value will display in the bottom of the grid table.
2. Input real values in the cells of the new row in the grid table.
The new row will be saved in to database table. Refresh the page, you will see all the changes you just made.

Extra Functionality

If you remember, we were going to create a sortable and filterable datagrid. This functionality can be achieved without changes in server-side logic. We enable client-side filtering and sorting by adding the next code to the /app/views/admin/view.rhtml file:

<script src="/javascripts/codebase/ext/dhtmlxgrid_filter.js" type="text/javascript" charset="utf-8"></script>
        ...
        <script type="text/javascript" charset="utf-8">
            var grid = new dhtmlXGridObject("grid_here");
            grid.setImagePath("/javascripts/codebase/imgs/");
            grid.setHeader("First name, Last name, Phone");
            grid.attachHeader("#text_filter,#text_filter,#text_filter"); //added !
            grid.setColSorting("str,str,str");  //added !

Finally, we have a datagrid which uses client-side logic to perform sorting and filtering of data, and manages data communication with a Ruby on Rails backend.

dhtmlxGrid and RoR Example: Editable Grid

dhtmlxGrid and RoR Example: Editable Grid

By clicking on the header you can sort the grid by any column. Typing text in input fields in the header will filter the grid records by entered text. When you edit records in the grid, the changes will be saved in the database automatically, as well as row addition and deletion (use the buttons below the grid).

The full source code of the resulting demo can be downloaded here.

Modifications for Ruby on Rails 3 Integration

1. In routes.rb:

resource :admin do
    collection do
      get 'view'
      get 'data'
      get 'dbaction'
    end
  end

2. Rename files:

  • data.rxml to data.xml.builder
  • dbaction.rxml to dbaction.xml.builder

 
3. Replace:

grid.load(/login/data”);

with:

grid.load(/login/data.xml);

4. Replace:

dp = new dataProcessor(/login/dbaction/);

with:

dp = new dataProcessor(/login/dbaction.xml);

 
Settings for Rails 3.1

If you want to use dhtmlxGrid with Rails 3.1 with asset pipeline feature, here are the additional details:

1. Make sure that asset pipeline feature is enabled in config:

config/application.rb:

# Enable the asset pipeline
    config.assets.enabled = true

2. Copy all files from ‘dhtmlxgrid/codebase’ to the corresponding folders of Rails application in the directory ‘vendor/assets’:

  • js files – copy in ‘vendor/assets/javascripts/dhtmlx’
  • css files – copy in ‘vendor/assets/stylesheets/dhtmlx’
  • images – copy in ‘vendor/assets/images/dhtmlx’

 
3. Change the path to images in grid:

grid.setImagePath("/images/dhtmlx/imgs/");

Here is the code sample for adding dhtmlxGrid files on a page:

        <%= javascript_include_tag 'dhtmlx/dhtmlxcommon.js' %>
        <%= javascript_include_tag 'dhtmlx/dhtmlxgrid.js' %>
        <%= javascript_include_tag 'dhtmlx/dhtmlxgridcell.js' %>
        <%= javascript_include_tag 'dhtmlx/dhtmlxdataprocessor.js' %>

        <%= stylesheet_link_tag 'dhtmlx/dhtmlxgrid.css' %>
        <%= stylesheet_link_tag 'dhtmlx/skins/dhtmlxgrid_dhx_skyblue.css' %>

The image below shows an example of directory tree for dhtmlxGrid, when you use Rails 3.1 with assets pipeline feature.

dhtmlxGrid Files - Directory Tree

dhtmlxGrid Files - Directory Tree

Posted by Stas Wolski

Comments

  1. Editable Datagrid for Ruby on Rails Buil... July 5, 2010 at 11:23 pm

    […] More: Editable Datagrid for Ruby on Rails Built with dhtmlxGrid « DHTMLX … […]

  2. Nicolas Blanco July 6, 2010 at 6:37 pm

    Interesting article thanks, this is a great start.

    But I don’t like the philosophy of adapting server side code to a client JS software.
    In the example, you take the “easy” way and create a custom controller action to handle all the possible default responses of the client plugin.

    In my opinion, the controller should be the same, with all the standard Rails actions (update, create, etc). Every client should connect and send requests to the server using the Rails conventions (in a RESTful way, unless you really don’t have the possibility to change or adapt the client JS).

    Maybe a better way to implement the plugin would be to catch user interactions with JS callbacks and use jQuery/Prototype to communicate with the server using standard AJAX calls.

    • Stas July 6, 2010 at 7:33 pm

      Yep, both approaches have their sense.
      It’s possible to change the code of client side to generate calls with different urls (actons) but it will require client side code customization which will add complexity and will not give any practical benefits on server side.

      More than that, all dhtmlx components uses the same data transfer protocol. So you can use nearly the same steps to load|save data in tree, treegrid, scheduler, dataview, charts.

      > Maybe a better way to implement the plugin
      Actually, behind the scene, the grid component catches js actions and produces ajax calls. And it’s possible to catch related events and produce custom calls instead of original one, but still I don’t see any practical reasons, except of architecture perfection.

  3. Tweets that mention Editable Datagrid fo... July 7, 2010 at 4:49 pm

    […] This post was mentioned on Twitter by Alex Hall, andrisetiawan. andrisetiawan said: Editable Grid for RoR with dhtmlxGrid http://www.dhtmlx.com/blog/?p=426 […]

  4. melvin July 7, 2010 at 5:28 pm

    Thanks , tutorial added in http://www.tutorialriver.com

  5. Bruce August 10, 2010 at 6:45 pm

    This is great! I was able to drive the grid with a list of strings stored in a session variable. However, the delete is not calling dbaction so I can remove the selected string from the session variable. It removes it from the screen but when I refresh it comes back because the session variable has not changed. Any ideas? Here is the script code:

    var grid = new dhtmlXGridObject(“data3”);
    grid.setImagePath(“/javascripts/codebase/imgs/”);
    grid.setHeader(“Platform“);
    grid.setInitWidths(“*”);
    grid.setSkin(“dhx_skyblue”);
    grid.init();
    grid.load(“/login/data”);
    dp = new dataProcessor(“/login/dbaction/”);
    dp.init(grid);

    /login/data is called to load the grid, but /login/dbaction/ is not called when I push “Delete” but the row is removed from the screen via grid.deleteSelectedRows()?

    Also how do you turn of editing of the cells?

    Thanks for any insights,

    –Bruce

    • ivan August 10, 2010 at 7:21 pm

      Bruce, be sure that :
      /javascripts/codebase/dhtmlxdataprocessor.js
      exists in the target location and is included on the page.

      Everything else looks correctly, and should work as expected (if the issue still occurs, please create a post at http://forum.dhtmlx.com ).

  6. Iļja Ketris August 29, 2010 at 9:37 pm

    There is some inconsistency in how DataConnector processes requests.
    The first GET is fine:

    Parameters: {“gr_id”=>”21”, “c0″=>”62”, “c1″=>”Another”, “c2″=>”0”, “!nativeeditor_status”=>”updated”}

    But when I change any other row I get:

    Parameters: {“gr_id”=>”22”, “c0″=>”63”, “c1″=>”Моё”, “c2″=>”0”, “!nativeeditor_status”=>””}

    Notice that the !nativeeditor_status is gone now.
    So just the first edit really works.

    • ivan August 31, 2010 at 4:52 pm

      If the issue can be stably reconstructed, please drop an email with details how it can be done to support (at) dhtmlx.com.
      Locally, we couldn’t reconstruct such behavior.

  7. stuti September 8, 2010 at 4:38 pm

    How the validations can be done in this datagrid?There is a dhtmlvalidation js.How can i make use of this.Can you give an example and explain.

  8. tesha September 13, 2010 at 2:40 pm

    How do we do validation for for more than 2 column, i m not able to display the error message for more than 2 columns ? Please help..

    • ivan September 13, 2010 at 3:29 pm

      There is no restrictions in the grid itself. The feature that works for 2 columns will be working for 10 columns the same way. If the problem repeats, please write to the Forum: http://forum.dhtmlx.com/

  9. Felipe October 9, 2010 at 3:23 am

    After creating the .rxml file and adding the following line

    grid.load(“/admin/data”); //added !

    I got this error:

    ActionController::RoutingError (No route matches “/admin/data”)

    Any suggestion?

    • ivan October 13, 2010 at 7:57 pm

      If you have created a new controller in the same steps as described above, then everything should work correctly.

      The issue can occur for the following reasons:
      – you have not created data method in controller
      – you are runing rails app not from the root url (http://localhost:3000)

  10. Marc January 17, 2011 at 10:58 am

    I’m trying to get this demo working with the ruby “Ramaze” framework (without rails) but I’m getting stuck on @users = User.all() to populate the grid.
    Does anybody know how Ramaze can load content from external XML datasource ?

  11. Shun January 19, 2011 at 11:13 pm

    For ROR users. If you guys are wondering why your XML doesn’t load when you apply it to your code, when your syntax looks good, your files are right, and you copied everything off this page; took me awhile to figure out why it didn’t work. If you use some sort of layout.erb – you will get an XML error. Try deleting the layouts in your view and layout “something” in controller.

    I kept on getting a HTTP Error 304 – Not modified – took me a day to figure out this stupid error

    THANK YOU FIREBUG <3

  12. Shun January 21, 2011 at 11:02 pm

    ruby 1.8.7, ror 2.3.8

    lets say for example I have a column type:
    grid.setColTypes(“dyn,ed,txt,price,ch,coro,ra,ro”);

    And I try to add it with:

    input type=”button” value=”Add” onclick=”grid.addRow(grid.uid(),’new user’)”

    When I click the add button – it doesn’t populate the grid with the check boxes and radios.

    any ideas?

    • ivan January 26, 2011 at 1:41 pm

      You need to provide some initial value for all columns:

      grid.addRow(grid.uid(),[‘new user’,”,”,”,1”,0,”])

      1 – if you want to have it checked, or 0 otherwise.

  13. Peter Moh April 4, 2011 at 5:34 pm

    It works if all column values provided as below.
    grid.addRow(grid.uid(),[‘new user’,”,”,”,1”,0,”])
    It does not automatically GET value from the user input (from the gird table).
    How can I let user input the values for grid.addRow() function?

  14. Peter Moh April 4, 2011 at 6:06 pm

    I should say sorry for my previous post.

    It works automatically as the author said.
    I suggest add more detail explanations:
    The way to make “inserted” function to work is
    1. Click button. A new row with some default value will display in the bottom of the grid table.
    2. Input real values in the cells of the new row in the grid table.
    The new row will be saved in to database table.
    Refresh the page, you will see all the changes you just made.

    • ivan April 26, 2011 at 1:34 pm

      We’ve added the explanations. Thank you for the suggestion.

  15. sent April 26, 2011 at 8:57 pm

    This is a great article.
    Guys I am a newbie , I need to customize the above grid and add a column lets say country at the end of the grid table and country has to be choosen from the combobox( US, FR,DE,…) . the country list will be stored in xml file.

    any idea please?

  16. Kumar August 6, 2011 at 4:15 pm

    I download the code and create the database.but i got error message(“no route matches”) so how can solve this problem.

    • Paul August 9, 2011 at 5:30 pm

      This problem is not related to the dhtmlx component, but is related to the default ROR mechanic – check that config/routes.rb contains route to the action in question.

  17. Mike Malloy September 2, 2011 at 12:47 am

    I am new to RoR. Is this tutorial for Rails v. 2.x? If so, what changes need to be made to make it work in Rails 3.0?

    I tried incorporating this into my Rails 3.0 application. I was able to get the grid to load in a .html.erb file using the code shown but when I added a data() method to my controller and then used a data.xml.builder file I got an error alert “Invalide xml”.

    Any pointers to a 3.0 version of this tutorial would be greatly appreciated. The grid looks like it could add a lot of polish to my application.

    • ivan September 6, 2011 at 6:34 pm

      Mike, we’ll update the article in the near time (week or two) and explain how to use the grid Rails 3.0 (we’ll let you know when it’s ready).

    • Ivan September 23, 2011 at 2:04 pm

      Mike, we’ve added the required modifications for RoR 3 in the end of the article.

  18. Rogie September 22, 2011 at 5:48 pm

    Hi. Thank you very much for this very informative tutorial. I’m also newbie in RoR. Like Mike, Im also using Rails 3.0. I did follow everything that was written in this tutorial, and unfortunately receive an error while loading the data — grid.load(“/admin/data”); — with this error message “Error type: LoadXML and Description: Incorrect XML”

    I hope that rails version 3 of this tutorial will come out soon.

    Again, thank you very much for this very informative tutorial. More power and God bless.

    • Ivan September 23, 2011 at 2:06 pm

      Rogie, please see the necessary changes for RoR3 in the end of the article. You should use:

      grid.load(”/login/data.xml”);
      • Anandhi May 18, 2012 at 5:03 pm

        hai….i ow only the basics of dhtml grid.i want to create a dhtmlxgrid in SAP-XMII using javascript…can u help me with the code…

  19. Sir Ivan September 24, 2011 at 5:53 am

    Sir

    Many thanks.

    I did follow all your instructions and everything works perfectly in Rails 3. This was really a big help specially for a newbie like me. Actually, I’m doing a project for our College using Open Source Technology (Ubuntu 10.04, Ruby 1.9.2 and Rails 3.0.9) and this is my first time to work with RoR.

    I will now try this grid using associations. Again, many thanks.

    More power and God bless you.

  20. vikram November 16, 2011 at 2:32 pm

    Our migration file

    class CreateUsers “John”,
    :last_name => “Smit”,
    :phone => “555 198 877”)
    User.create(
    :first_name => “Stanislav”,
    :last_name => “Wolski”,
    :phone => “456 456 454”)

    end

    def self.down
    end
    end

    then below is our view file

    var grid = new dhtmlXGridObject(“grid_here”);
    grid.setImagePath(“/javascripts/codebase/imgs/”);
    grid.setHeader(“First name, Last name, Phone”);
    grid.setInitWidths(“100,100,*”);
    grid.setSkin(“dhx_skyblue”);
    grid.init();
    grid.load(“/admin/data.xml”);

    After running in browser(chrome). the dialouge box will be shown error as below

    Error type:LoadXML
    description: incorrect XML

    Thanks

    • Ivan November 18, 2011 at 11:19 am

      In you code:

      grid.load(“/admin/data.xml”)

      but the original code expects that you will call:

      grid.load(“/admin/data”);

      It loads not the static data.xml file, but trigger /admin/data action, which will generate xml data based on database content.

    • sharath April 10, 2012 at 12:50 pm

      Hi dagar vikky

      grid.load(”/admin/data.xml”);

      instead of this , change the line as follows

      grid.loadxml(”../../admin/data”);

      Thanks

      sharath RP

  21. Chris January 18, 2012 at 8:42 pm

    Thank you for this — I was able to get data to successfully load into the grid using Rails 3. That said, I am now stuck on what seems like a simple issue. I would like to make my grid read-only and create a button to link to a separate view to edit the selected record. I have been unable to figure out how to pass the selected record from the grid to the controller when opening the new view. Since no data change is happening in the grid I have been unable to use the datacontroller to sync the information server-side. Any help would be appreciated.

  22. Daniel February 3, 2012 at 4:08 pm

    I have got a stabililty issue with webrick server. It seems to crash due to a “econnreset”-error that appears randomly.

    I described it in detail on the following page:
    http://stackoverflow.com/questions/9128725/dhtmlxgrid-editable-grid-errnoeconnreset

    Help would be greatly appreciated! =)

  23. sharath February 18, 2012 at 9:32 am

    Anyone please suggest the suitable server for ruby on rails

  24. Motoko March 12, 2012 at 1:21 pm

    I wanted to thank you for the work you have done here. Following your instructions I have been able to complete the tutorial using ROR 3.1, but i have an annoyng problem.

    When I load the view with the grid for the first time all work’s fine, but if I reload it ruby server crashes. If I go to the view, then i load a different page I don’t get any error when i return to the grid view, but i can’t refresh it without getting a ruby crash.

    ¿Has this happened anyone else?

  25. charan May 9, 2012 at 8:54 am

    I am able to retreive the data from the database using linq.and it is displaying in the output but I am not able to insert these values into the grid.These are displaying outside the grid .how can i insert this data into the grid?

  26. charan May 9, 2012 at 10:43 am

    mygrid = new dhtmlXGridObject(‘gridbox’);
    mygrid.setImagePath(“../../dhtmlx/imgs/”);
    mygrid.setHeader(“ID,Name,Email,Salary,age,country,Married,Head,StartDate,WebsiteLink”);
    mygrid.setInitWidths(“50,100,150,50,50,100,50,50,100,150”);
    mygrid.setColAlign(“center,center,center,center,center,center,center,center,center,center”);
    mygrid.setColTypes(“ed,ed,ed,price,ed,co,ch,ra,dhxCalendarA,link”);
    mygrid.setColSorting(“int,str,str,dec,int,str,bit,bit,date,str”);
    mygrid.init();
    @foreach (var item in Model)
    {

    @item.ID
    @item.Name
    @item.Email
    @item.Salary
    @item.Age
    @item.Country
    @item.Married
    @item.StartDate
    @item.WebsiteLink

    }

    By using the foreach I am able to get theb data in the output.but i want to load this data into the grid.

    Any Suggestions,

  27. ann June 14, 2012 at 2:00 pm

    i m using rails 3. have problem loading xml. it gives the error “Error type: LoadXML
    Description: Incorrect XML”
    code i have used is:

    var grid = new dhtmlXGridObject(“grid_here”);
    grid.setImagePath(“/javascripts/codebase/imgs/”);
    grid.setHeader(“First name, Last name, Phone”);
    grid.setInitWidths(“100,100,*”);
    grid.setSkin(“dhx_skyblue”);
    grid.init();
    grid.load(“admin/data.xml”);

    can any one please help me?…….

  28. Nikita Singh January 29, 2013 at 4:40 pm

    I want to make one of the column as date picker. how to do that?

    • Nikita Singh January 29, 2013 at 6:41 pm

      Got it !

  29. John Baycroft February 1, 2013 at 12:22 am

    I have been using DHTMLXGrid happily for several small projects to display information for single tables.

    I am now attempting to implement a nested table.

    the path I am trying to feed to the grid.load is

    grid.load(“/user/:user_id/task/:task_id/data.xml”);

    How would I feed the :user_id and :task_id into grid?

    Thanks!

  30. Nico April 24, 2013 at 1:19 pm

    Hi, thank you for the useful tutorial. I’m using rails 3.2.
    I don’t understand where the /login/ view comes from.

    In the bottom of the tutorial is written to “replace grid.load(”/login/data”);” …
    Replace ? I’ve never seen any /login/data so far…Should I create another view? Rename every single file(views, controllers etc) from ‘admin’ to ‘login’?

    Sorry I’m noob, but I don’t think that using the word ‘replace’ for something that did not exist before is correct.

    Thanks a lot in advance for the help

    • Ivan April 28, 2013 at 3:24 pm

      Nico, this article uses outdated methods of defining paths. In the current version of Rails you need to define paths on which the app will respond in the file config/routers.rb, for example:

      match “/data”, :to => “grid#index”, :via => :get

      where “/data” is a relative path
      “grid#index” – the name of the grid controller and method ‘index’
      parameter :via defines the method of request

      You can find more about the configuration of file routers.rb here:
      http://api.rubyonrails.org/

      In this case, to make a selection from the database and send it to the client as XML, you need to do the following:

      grid.load(“/admin/data”);  – it states that the server should respond to the request “/admin/data”

      then in “config/routers.rb” should be added:

      match “/admin/data”, :to => “admin#data”, :via => :get

      So you need to create /app/controller/admin_controller.rb: that includes method data and the file /app/views/admin/data.rxml:

      • Nico May 3, 2013 at 7:49 pm

        Thank you Ivan.

        I’m not sure we are in sync.

        I’m using Rails 3.2.13 and ruby 1.9.3p392 . Does it matter?

        Adding that line to the routes gets me an error when launching
        rails s
        .

        Now my routes looks something like this… Where should I add your lines?

        StartupgenomeSurvey::Application.routes.draw do

        resource :admin do
        collection do
        get ‘view’
        get ‘data’
        get ‘dbaction’
        end
        end

        • Nico May 3, 2013 at 7:52 pm

          PS : I get this error :

          /config/routes.rb:27: syntax error, unexpected $end, expecting keyword_end
          match “/admin/data”, :to => “admin#data”, :via => :get

          PPS : the tutorial tells me to rename the file data.xml.builder , while you mention data.xml. I’m getting frustrated and confused here :)

          Thanks a lot for your help!

  31. Allen Maxwell June 24, 2013 at 8:25 pm

    I kept having trouble with the images being found (specifically sort_desc.gif) when i tried plugging in the code as described. I tried every variation i could think of but it couldn’t find the file. eventually i simply added all the images to the public/images/dhtmlx/imgs dir and we were good to go. HTH

    btw, i’m on rails 3.2.13 and ruby 1.9.3+

  32. Allen Maxwell June 24, 2013 at 8:25 pm

    I kept having trouble with the images being found (specifically sort_desc.gif) when i tried plugging in the code as described. I tried every variation i could think of but it couldn’t find the file. eventually i simply added all the images to the public/images/dhtmlx/imgs dir and we were good to go. HTH

    btw, i’m on rails 3.2.13 and ruby 1.9.3+

Leave a Reply