How to load selective fixtures to db in rails

All of you must know how to load fixtures to db

rake db:fixtures:load 

To load a subset of your fixtures to your projects db

rake db:fixtures:load FIXTURES=users,stores

Leave a Comment

Star rating in ruby on rails

Recently I needed to implement star rating system for one of my project I am working on.

If you are not familiar with a star rating system, its simply a method of voting using (usually) 5 stars in a row, which will change colour as you hover over them indicating the level at which to rate something. You may think a simple rollover would accomplish this but difficulty arises because as you rollover each star it should stay highlighted while you light up the next one and so on until the end of the row of stars.

If this doesnt make much sense to you then take a look at what we are going to achieve in this article. (I will leave the server-side coding to someone more knowledgeable and we will just concentrate on the visual aspects of making this effect happen. )

As you can see from the demo the stars stay hovered as you rollover each one. However, as mentioned earlier, the complicated part is that as each star is hovered it should stay alight while the next one is hovered so that if you start at the left side then 1,2,3,4 and 5 stars will be alight as you traverse the row. Usually a rollover will only be active on the anchor that the pointer is currently over making previous anchors lose their focus and thus their hover effect disappear.

Install the acts_as_rateable plugin.

Run the following from the root of your Rails app to install the plugin.

script/plugin install http://juixe.com/svn/acts_as_rateable
or
http://rubyforge.org/projects/rateableplugin/

Create the table(migration) to store rating into database

class CreateRatings< ActiveRecord::Migration

def self.up
create_table :ratings, :force => true do |t|
t.column :rating, :integer, :default => 0
t.column :created_at, :datetime, :null => false
t.column :rateable_type, :string, :limit => 15,
:default => “”, :null => false
t.column :rateable_id, :integer, :default => 0, :null => false
t.column :user_id, :integer, :default => 0, :null => false
end

add_index :ratings, [”user_id”], :name => “fk_ratings_user”
end

def self.down
drop_table :ratings
end

end

Model

models rateable

I was trying to add a rating system for the model Picture. Yours can obviously be whatever you like but from here on out I’ll be using Picture. So add acts_as_rateable to your model.

class Picture < ActiveRecord::Base
acts_as_rateable

end

Controller to handle the rating
class RatingController < ApplicationController

def rate
@picture = Picture.find(params[:id])
Rating.delete_all(["rateable_type = 'Picture' AND rateable_id = ? AND user_id = ?",
@picture.id, current_user.id])
@picture.add_rating Rating.new(:rating => params[:rating],
:user_id => current_user.id)
end

end

Views

Create the partial /views/rating/_rating.rhtml

  1. <%= number_with_precision(picture.rating, 1) %>/5 Stars</p>  
  2. <ul class=’star-rating’>  
  3. <li class=‘current-rating’ style=’width:<%= (picture.rating * 30).to_i -%>px;’><br />  
  4.           Currently <%= number_with_precision(picture.rating, 1) %>/5 Stars.  
  5.         </li>  
  6. <li>  
  7.         <%= link_to_remote( “1″, {:url => { :controller => “rating”,<br />  
  8.             :action => “rate”, :id => picture.id, :rating => 1}},<br />  
  9.             :class => ‘one-star’, :name => ‘1 star out of 5′) %>  
  10.     </li>  
  11. <li>  
  12.         <%= link_to_remote( “2″, {:url => { :controller => “rating”,<br />  
  13.             :action => “rate”, :id => picture.id, :rating => 2}},<br />  
  14.             :class => ‘two-stars’, :name => ‘2 stars out of 5′) %>  
  15.     </li>  
  16. <li>  
  17.         <%= link_to_remote( “3″, {:url => { :controller => “rating”,<br />  
  18.             :action => “rate”, :id => picture.id, :rating => 3}},<br />  
  19.             :class => ‘three-stars’, :name => ‘3 stars out of 5′) %>  
  20.     </li>  
  21. <li>  
  22.         <%= link_to_remote( “4″, {:url => { :controller => “rating”,<br />  
  23.             :action => “rate”, :id => picture.id, :rating => 4}},<br />  
  24.             :class => ‘four-stars’, :name => ‘4 stars out of 5′) %>  
  25.     </li>  
  26. <li>  
  27.         <%= link_to_remote( “5″, {:url => { :controller => “rating”,<br />  
  28.             :action => “rate”, :id => picture.id, :rating => 5}},<br />  
  29.             :class => ‘five-stars’, :name => ‘5 stars out of 5′) %>  
  30.     </li>  
  31. </ul>  
  32. <p>

A little RJS

Create the file /views/rating/rate.rjs
page.replace_html “star-ratings-block”, :partial => ‘rating/rating’, :locals => { :picture=> @picture }

This will replace the star ratings with the partial we created previously in order to reflect any rating changes made by the submission.

Render the partial in one of your views.
“rating/rating”, :locals => { :picture => @picture } %>

This needs @picture(or whatver you’re going to be using) in order to function.

Remember to add the css and image
/* styles for the star rater */
.star-rating{
list-style:none;
margin: 0;
padding:0;
width: 150px;
height: 30px;
position: relative;
background: url(/images/star_rating.gif) top left repeat-x;
}
.star-rating li{
padding:0;
margin:0;
float: left;
}
.star-rating li a{
display:block;
width:30px;
height: 30px;
text-decoration: none;
text-indent: -9000px;
z-index: 20;
position: absolute;
padding: 0px;
}
.star-rating li a:hover{
background: url(/images/star_rating.gif) left center;
z-index: 2;
left: 0px;
border:none;
}
.star-rating a.one-star{
left: 0px;
}
.star-rating a.one-star:hover{
width:30px;
}
.star-rating a.two-stars{
left:30px;
}
.star-rating a.two-stars:hover{
width: 60px;
}
.star-rating a.three-stars{
left: 60px;
}
.star-rating a.three-stars:hover{
width: 90px;
}
.star-rating a.four-stars{
left: 90px;
}
.star-rating a.four-stars:hover{
width: 120px;
}
.star-rating a.five-stars{
left: 120px;
}
.star-rating a.five-stars:hover{
width: 150px;
}
.star-rating li.current-rating{
background: url(/images/star_rating.gif) left bottom;
position: absolute;
height: 30px;
display: block;
text-indent: -9000px;
z-index: 1;
}

Image for your CSS

star_rating.gif

Comments (7)

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

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

Comments (3)

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

Comments (1)

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. Read the rest of this entry »

Comments (9)

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 << [c.id, c.title, c.job_title, c.first_name, c.last_name]
end

end
report.rewind
send_data(report.read,:type => ‘text/csv; charset=iso-8859-1; header=present’,:filename => ‘report.csv’, :disposition =>’attachment’, :encoding => ‘utf8′)

end

View :

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

<% end -%>

Comments (5)

Hello world!

Welcome to Satish Chauhan’s blog. This is my first post.

<!– Kontera ContentLink(TM);–>
<script type=”text/javascript”>
var dc_AdLinkColor = ‘orange’ ;
var dc_UnitID = 14 ;
var dc_PublisherID = 20113 ;
var dc_adprod = ‘ADL’ ;
</script>
<script
src=”http://kona.kontera.com/javascript/lib/KonaLibInline.js” type=”text/javascript”>
</script>
<!– Kontera ContentLink(TM) –>

Comments (2)