Posts filed under ‘Rails’

How to Paginate With Ajax

Pagination is a very common task in web application development. But sometimes we need to paginate something with ajax request. The interest to use Ajax for this is to provide a dynamic interface which doesn’t need to reload the entire page when next results(page) displayed. Ajax is really nicely integrated with Rails, and using it is very easier with this great framework. To work with ajax requests your browser must be enabled to handled java script requests. I knew two methods for that problem.

This is posted on satish’s blog

For more details click here

Advertisements

August 8, 2007 at 10:05 am Leave a comment

How to import CSV file in rails

How to import CSV file in rails?

The CSV text-file format is a common choice for both import and export when performing data migrations. What if you want to import CSV files within a Rails application?

Here is the code that allow you to upload CSV data onto the MySQL database from the web interface
This code save data direct to database without saving it to temp file

Controller:

    require 'csv'

   def csv_import 
     @parsed_file=CSV::Reader.parse(params[:dump][:file])
     n=0
     @parsed_file.each  do |row|
     c=CustomerInformation.new
     c.job_title=row[1]
     c.first_name=row[2]
     c.last_name=row[3]
     if c.save
        n=n+1
        GC.start if n%50==0
     end
     flash.now[:message]="CSV Import Successful,  #{n} new records added to data base"
   end

View:
your view will look like

 <% form_for :dump, :url=>{:controller=>"customer_informations", :action=>"csv_import"}, :html => { :multipart => true } do |f| -%>
 <table">
   <tr>
     <td>
      <label for="dump_file">
        Select a CSV File :
      </label>
     </td>
     <td >
       <%= f.file_field :file -%>
     </td>
   </tr>
   <tr>
     <td colspan='2'>
       <%= submit_tag 'Submit' -%>
     </td>
   </tr>
 </table>
<% end -%>

July 18, 2007 at 6:17 pm 9 comments

Varify Email address Format

Varify Email address Format

Useful expressions for email address validation

Matches a limited version of the RFC 2822 addr-spec form.

/A(?:[w!#$%&'*+-/=?^`{|}~]+.)*[w!#$%&*+-/=?^`{|}~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]?!.)){0,61}[a-zA-Z0-9]?.)+[a-zA-Z0-9](?:[a-zA-Z0-9-](?!$)){0,61}a-zA-Z0-9]?)|(?:[(?:(?:[01]?d{1,2}|2[0-4]d|25[0-5]).){3}(?:[01]d{1,2}|2[0-4]d|25[0-5])]))Z/i

satish chauhan

July 3, 2007 at 4:37 pm 2 comments

Multiple Checkboxes with HABTM

Has and Belongs to Many with Multiple Check boxes

So if you are trying to do a multiple select of checkboxes and using habtm in your project, but when you submit the form, only one value was available in your controller. While you try to edit records in database but because of some error you get back to the pre field form and you found that the checkboxes checked by you gone ,then here’s the solution

Model:

	class Customer < ActiveRecord::Base
		has_and_belongs_to_many :intrests
	end

Controller code:

class CustomersController < ApplicationController
   def create
      if request.post?
         @customer=Customer.new(params[:customer])
         @customer.save
      end
   end

   def edit
      @customer=Customer.find_by_id(params[:id]) if params[:id]
      if @customer
         if request.post?
            if @customer.update_attributes(customer)
               flash.now[:message]="Update successfully "
            end 
         end
      else
        flash[:message]="Page requested by you does not exists"
      end
   end
end

Your View:

 <% form_for :customer,  do |f| -%>
    First Name:
      <%= f.text_field :first_name  -%>
    Last Name:
      <%= f.text_field :last_name -%>
      <% for  intr in total_intrests -%>
         <%= check_box_tag "customer[interest_ids][]", "#{intr.id}", interest(intr) -%> # interest is a helper method
         <%= "#{intr.name}" -%>
      <% end -%>
   <% end -%>

helper method

   def interest(i)
      if @customer
         @customer.interests.include?(i)
      else
        false
      end
   end

View generate a checkbox for every interest(all_interest=Interest.find(:all)). The name of the input is significant obviously. The trailing “[]” on the name means the end result will be the list of checked ids. This list will be stored on the @params[‘customer’] hash with the key ‘interest_ids’. When the controller calls @customer.update_attributes(@params[:customer]), it tries to call @customer.key= for each of the keys on @params[:customer]. What’s important to realize is that these keys don’t have to actually be attributes on the Customer model. All that’s important is that there’s a key= method on the model. Model automatically contains a “collection_ids=” method for habtm and has-many associations.

This method will load the objects identified by the ids and call the “interest=(list)” method on the model with the freshly loaded list. This method in turn, will compare the list to the current list of interests and delete/add interests as necessary. (more…)

June 29, 2007 at 9:36 am 12 comments

How to generate CSV files in Rails

Controller code :

require 'csv'
   def export_to_csv@customers=CustomerInformation.find(:all)
      report = StringIO.new
      CSV::Writer.generate(report, ',') do |title|
         title << ['Id', 'Title', 'Job Title', 'First Name', 'Last Name']
         @customers.each do |c|
            title < 'text/csv; charset=iso-8859-1; header=present',:filename => 'report.csv', :disposition =>'attachment', :encoding => 'utf8')
         end
      end
   end

View:

    <% form_tag({ :action =>  :export_to_csv })do -%>
       <%= submit_tag "Export To CSV" -%>
    <% end -%>

June 28, 2007 at 12:30 pm 4 comments


Calendar

December 2017
M T W T F S S
« Aug    
 123
45678910
11121314151617
18192021222324
25262728293031

Posts by Month

Posts by Category