Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Wednesday, 20 February 2013

Giving name to excel sheet while exporting it- rails 3

You may want to give file name to your excelsheet when you are exporting it. Suppose you want to give the todays date and time as its name. Then do the following:

Suppose export is the method in which you have written the code for exporting excel sheet then do the following:


    def export
       time = Time.now
       time.strftime("%Y-%m-%d %H:%M:%S")
 
      respond_to do |format|
      format.html

      format.xls { headers["Content-Disposition"] = "attachment; filename=\"#{time}"+".xls"}
    end

Monday, 4 February 2013

Using Dhtmlx datagrid in rails 3 with calendar and combo box (select box)as column type

Earlier I wrote about using a simple dhtmlx data grid in rails 3. The column type was text box which where editable. As I explored it more I found other column types which can be used with datagrid.


Calendar as column type
To use calendar as column type you have to add some of the js and css. These files can be easily downloaded from the dhtmlx website. Download the zip file and copy the below js and css inside your assests javascript and stylesheets folder.

Javascript files:
dhtmlxgrid/codebase/excell/dhtmlxgrid_excell_dhxcalendar.js
dhtmlxgrid/codebasedhtmlxcommon.js
dhtmlxgrid/codebase/calendar/dhtmlxcalendar.js

CSS files:
dhtmlxCalendar/codebase/skins/dhtmlxcalendar_dhx_skyblue.css
dhtmlxgrid/codebase/calendar/dhtmlxcalendar.css


Now while initializating the datagrid specify the  coltype as dhxCalendar


            var grid = new dhtmlXGridObject("grid_here");
            grid.setImagePath("");
            grid.setHeader("Name, Amount");
           
            grid.setColSorting("str,str");
            grid.setInitWidths("150,150");
            grid.setSkin("dhx_skyblue");
            grid.setColTypes("dhxCalendar,ed");

            grid.init();
            grid.load("/decoration/data?decoration="+deco);
            
            dp = new dataProcessor("/decoration/dbaction?decoration="+deco);
            dp.init(grid);

Note:- If you get some error like undefined coltype or somthing. This means that you have not included the correct js. Please check again for all the js files.


Combo box/list box/select box as column type

Specify the setColTypes as "co" if you want to add more options while editing datagrid or else specify "coro" to make it read only.

To add default options to the combo box do the following



      var grid = new dhtmlXGridObject("grid_here");
            
            grid.setImagePath("");
            grid.setHeader("Select number");

            grid.enableMultiselect(true)
            grid.enableLightMouseNavigation(true);
            grid.setInitWidths("100")
            grid.setSkin("dhx_skyblue");
            grid.enableAutoHeight(true);
            grid.enableMultiline(true);
        
            grid.setColTypes("coro");

            var combo1 = grid.getCombo(1); //Here 1 is the id of the column
        
            combo1.put(0,"zero"); // the first data is the value and the second is the data displayed in the dropdown
            combo1.put(2,"two");
    
            grid.init();
      
            grid.load("/visit/data?visit="+deco);
            dp = new dataProcessor("/visit/dbaction?visit="+deco);
            dp.init(grid);



Wednesday, 23 January 2013

Data grid for rails 3 !!

Recently in my project I was trying to use jqgrid or datagrid kind of thing . I selected datagrid and here is the procedure to use it.

Step 1: Generate a controller, say admin


Step 2: Generate a model , say user with three column suppose first_name,last_name,phone


Step 3: Run rake db:migrate


Step 4: Download the jquery from here datagrid. And copy only the 
dhtmlxcommon.js dhtmlxdataprocessor.jsdhtmlxgrid.js and dhtmlxgridcell.js to your app/assests/javascript folder. For css copy the dhtmlxgrid.css and dhtmlxgrid_dhx_skyblue.css in your stylesheet folder.
Also copy the images to your images folder.

Step 5: In controller add an action called view like this :-

        
        class AdminController < ApplicationController
           def view
           end
       end


Step 5: Add a view.html.erb with the following code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <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>

Step 6: Modify your routes.rb file to add this

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

If you go to your http://localhost:3000/admin/view you can now see the overall structure of the data grid.

To fill the data with the data grid do the following:


Step 7: Add a new action data in your admin controller

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


Step 8: Add the view part of that action in  /app/views/admin/data.xml.builder

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

Step 9: Add one more line to your view code,

    <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>

To save grid data do the following:-

Step 10: Add one more action dbaction to your controller-


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 

Step 11: For this dbaction add the view part in  /app/views/admin/dbaction.xml.builder


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

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


Step 12: Modify the view.html.erb file like this


    <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>


Step 13: Go to http://localhost:3000/admin/view and now you can see the the data grid with add and delete functionality




Point to be noted:-
  • Make sure  you change the path of the images in the css file so that images gets refelected in your view part.
  • This is just a basic example, more functionalty can be added if you refer to the documentaion of the datagrid


Tuesday, 15 January 2013

Testing paperclip with rspec

This post cover the basic testing of paper clip gem in the controller. Since I am new to rspec so I may not be able to cover it in detail with many test cases now but for beginners, I hope its useful.

Suppose you are testing the new function of your controller then the steps will be like this:

  1.  Add a describe in your decorations_controller_rspec.rb.
    Note: Decoration here is the name of my controller, which creates a decoration with a name, year of that decoration and expense.Expense here is an excel sheet which is getting uploaded through paperclip gem.

    describe "#new" do
        it "must take 4 parameter and returns a decoration object" do
         get "new"
            @decorations=Decoration.new(:name=>'decoration',:year=>'2012',:zone_id=>'1',:expense=> File.new(Rails.root + 'spec/fixtures/test.xls'))
           @decorations.should be_an_instance_of Decoration
        end
    end
  2. Create a folder fixtures inside spec directory of your application and add any xls file suppose test.xls. 
  3. Its done. You rspec will pass the test case.


Monday, 14 January 2013

Assets pre compilation error while deploying on heroku

In this post, I am going to address one of the problem I faced while using jquery in my ruby on rails project.

I was using Data Table and Multiselect jquery on my ruby on rails application. It was working fine on my local host. However when I pushed it to github and deployed it on Heroku. It started giving me the following assets pre compilation error.


Your bundle is complete! It was installed into ./vendor/bundle
       Cleaning up the bundler cache.
-----> Writing config/database.yml to read from DATABASE_URL
-----> Preparing app for Rails asset pipeline
       Running: rake assets:precompile
       rake aborted!
       could not connect to server: Connection refused
       Is the server running on host "127.0.0.1" and accepting
       TCP/IP connections on port 5432?


The reason for this compilation error can be be anything. I googled it around and found many solution like
  • Solution 1
    Changes in application.rb-In application.rb file, make config.assets.initialize_on_precompile = false. This option prevents the Rails environment to be loaded when the assets:precompile task is executed. Because Heroku precompile assets before setting the database configuration, you need to set this configuration to false or you Rails application will try to connect to an unexisting database.
  • Solution 2
    Assets group in gemfile
    - keeping the jquery gems under assets group in your gemfile.
  • Solution 3
    Check your jquery and css
    - Make sure your css file and jquery files are correct and is in proper format. Even an extra semicolon (;) or brackets will fail the assets pre compliation. Even if you have downloaded a jquery from authentic source it may happen that it have some bugs which will work on local host but not on heroku. (Happened with me)
  • Solution 4
    Remove all the unused jquery from github- It might be possible that you might have been trying many jqueries with your application. You might have pushed this jqueries to github. But later on deleted it from your application in you local machine but didnt do same for the github.
    Use rm command to remove all the unused files.
    Note:- If you think that by deleting files from your local machine and pushing again to github will delete the files from the github also then you are wrong !!! (YES !! I was WRONG). I thought adding, commiting and pushing will remove the files from github also . (Since I am a fresher and new to github, I hope this type of mistake is acceptable :P )
I tried solution 1 2 & 3 but none if them was working. for me. During pre-compliation it was giving me the css error even after I removed all the css files from my local machine and pushed it to heroku.

So yes...I tried the solution 4 removed the conflicting css and jqueries from github and yeah there was no precompliation error !!

So what worked for me was to remove all the unused files css files and jquery files from your local machine and github.