Saving Arrays into Table

Well, this must be common to all, as all of us has implemented this kind of feature somewhere in our projects.. But I found it challenging couple of times to implement this.. so I thought to share this small piece of code with you. Hope it helps someone..

Requirement: In this small project we are going to store multiple arrays into the database as each array will create a new row.

Let’s see how it works..

Here is my view(in your case it could be any)

<select name=”contacts_id[]” id=”contacts_id”>
<% current_user.contacts.all.each do |contact| %>
<%= contact.name %>
<% end %>
<%= channel.name %>

Now in this case we have two arrays one is for contact_id and another one is for channel_id, Let’s see how we will store those values into the table:

def create
@contacts_channels = []
params[:contact_id].each_with_index do |contact, i|
@contacts_channels[i] = ContactChannel.new
@contacts_channels[i].contact_id = contact_id
@contacts_channels[i].channel_id = params[:channel_id][i]
@contacts_channels[i].save
end
end

So what happens here? suppose you have an array of contact_id like this:
contact_id = [4,5,6]
and array of channel_id like this:
channel_id = [10, 11, 12]

So with the above script your values should go into the table like this
contact_id channel_id
4 10
5 11
6 12

What makes me puzzled here is, in case of relationship here like
Contact has_many :channels
how will this exact scenario works?

Please let me know your feedbacks, suggestions and queries. Your comment means lot to me.

rake aborted: no such file to load mysql

Programmers who work mostly on windows have seen this kind of errors many times.. as a windows programmer I have been through many sites and collect d relevant data, now I am showing it to you..

The errors which might come to you something like this:
no such file to load mysql
rake aborted: no such file to load mysql
The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql
Could not find RubyGem rake-compiler (~> 0.5)

To solve such problems follow these steps:
Step 1. Update rubygems to the latest version(like I upgraded it to 1.3.5).
Step 2: install rake-compiler(by gem install rake-compiler).
Step 3: if already installed hoe gem update it(gem update hoe) or install a fresh one.
Step 4: Download libMySQL.dll from here and copy it into C:/ruby/bin or wherever your ruby is installed, but make sure it should be in bin directory.
Step 5: Stop the mysql service, from Control Panel -> Administrative tools -> services -> mysql, and then restart it.

That’s it. You are done, after all these steps you can try
rake db:migrate
Suppose if that doesn’t work then after 4th step, stop the mysql service and restart your system.

I welcome all of you to post your comments, feedbacks, queries

Cheers!!
Puneet Pandey

Send Tweets from rails application

Hey all,

I hope this article will help you if you want to send tweets from your rails application. I have used couple of gems and plugins for that, will describe you those in this tutorial.

AIM: We have a rails application which will allow twitter user to log-in. Once the user logged-in he/she can send tweets from your rails application.

DEPENDENCIES: 1. geokit-rails [Plugin]
2. ym4r-gm [Plugin]
3. twitter4r [Gem]
4. twitter-search [Gem]
5. twitter-console [Gem]
6. google-geocode [Gem] [Optional]

INSTALLATION:
1. Install twitter4r (gem install twitter4r[for windows user], sudo gem install twitter4r[for linux users])
2. Install twitter-search (sudo gem install dancroak-twitter-search -s http://gems.github.com)
3. Install twitter-console *for linux users only
[Follow this: http://www.fsckin.com/2008/03/31/twitter-clients-for-linux/]
[and this: http://blog.guillermoamaral.com/2007/03/18/twitter-console-update/]
4. Install google-geocode (sudo gem install google-geocode)
5. Install goekit-rails
5.1 ruby script/plugin install git://github.com/andre/geokit-rails.git
5.2 Add this line to your environment.rb: config.gem “geokit”
5.3 Tell Rails to install the gem: rake gems:install
(for more details visit this link: http://github.com/andre/geokit-rails/tree/master)
6. Install ym4r_gm (ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm)
[if you get trouble in installation follow this: http://ym4r.rubyforge.org/]

So we have a base setup for our rails application. Now lets have some code.
First of all lets create few models as well as migrations tables:
1. ruby script/generate model Keyword
2. ruby script/generate model Location
3. ruby script/generate model Post
4. ruby script/generate model User
5. ruby script/generate model Techtwit
6. ruby script/generate migration sessions

After creating all the above steps lets create some columns for our tables:
1. for keywords: timestamps
2. for locations: address:text, timestamps
3. for posts: message: text, timestamps
4. for users: username:string, password:string
5. for techtwits: twitter_id:string, timestamps
6. for sessions: session_id:string, data:text, timestamps
6.1 add_index :sessions, :session_id
6.2 add_index :sessions, :updated_at

Follow this Tutorial to finish-off this application.

Minimise URL in Ruby

Does it looks odd?? You have so many websites which allows you to minimise your url like tinyurl, bit.ly etc etc list is endless, but what if you get some API of those to work with so you can minimise the url with your rails application or as a stand-alone ruby program??

Bit.ly comes with that. It provides ruby programmers an interface by which they can minimise the url. Wondering How? see it in action..

I am creating a simple ruby program here, if you want you can use it in your application…

All you need is json and open-uri to finish it off.

require ‘open-uri’
require ‘json’

code=’https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=zpwhtygjntrz&scc=1&ltmpl=default&ltmplcache=2&hl=en’
user=’YOUR USERNAME’
apikey=’YOUR API KEY’
version=’2.0.1′
url = “http://api.bit.ly/shorten?version=#{version}&longUrl=#{code}&login=#{user}&apiKey=#{apikey}”
buffer = open(url, “UserAgent” => “Ruby-ExpandLink”).read
result = JSON.parse(buffer)
shorturl = result['results']['shortUrl']

That is it. Run this program in console/command prompt, where ever you want to see the output.

Post your queries, suggestions
Puneet

Bulk Upload with Rubyzip

Hi guys,

Its been a long time since I posted any article. This time I come up with Interesting Tutorial which is Bulk Upload. Normally in most of the sites we have seen that there is a file upload field where we can upload a zip file and it will extract automatically.

Now the Point is How it can be done is Ruby on Rails? The answer is very simple, all we need are two gems + few lines of code. Wondering How?? See this in action…

Install two gems first:

for Linux Users:

1. sudo gem install rubyzip

2. sudo gem install fastercsv

for windows users: remove sudo and install above gems.

now open up your rhtml page and write down the following code:

<% form_for :file_upload,:url => {:controller=>'bulkupload',:action=>'upload_file'}, :html => { :multipart => true, :target => "frame", :id => "file_upload" } do |f| %>
<input type="file" name="file_upload_product[file_name]"/>
<input type="submit" value="Upload"/>
<%end%>

Now Open up your bulkupload controller and create method upload_file in that

require 'faster_csv'
require 'fileutils'
class BulkuploadProductController < ApplicationController
  def bulk_upload
    begin
     @file=FileUpload.new
     @file.file_name=params[:file_upload_product]['file_name']
     if @file.save
      responds_to_parent do
       render :update do |page|
        page << "$('file_uploaded_id').value="+@file.id.to_s
        page.replace_html 'upload_message',"<span class='heading4'>File has been moved to server. Please click submit to upload.</span>"
       end
      end
     else
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Please Upload File</span>"
       end
      end
     end
     rescue Exception=>e
      puts "ERROR :: bulkupload_products :: upload_file :: #{e.to_s}"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Some internal Error has occurred</span>"
       end
      end
    end
  end
end

Let me know if you have any doubts

Fetch Rss Feeds in Rails

Heya Guys,

Gossshh, I had lot of work, woooooohhh, but now I am over with that and thought to write a new post for all of you… I am very thankful to all of you that you are appreciating my articles and giving me such a good response, It is not only developing my confidence but also I want to bring more and more articles in rails, so that It will help you to know the magic behined RoR.

So let me start it. In this post of mine I will Fetch Rss Feeds from Techcrunch with open-uri, Interested to know, let’s see how it works…

Create an application, open your environment.rb file and add this line at the bottom:
RSS_FEED = ‘http://feedproxy.google.com/TechCrunch’

Now create a controller, in my case I have feeds_controller with fetch method, Open it and add below lines
class FeedsController < ApplicationController
require ‘rss/2.0′
require ‘open-uri’
def fetch
feed_url = “#{RSS_FEED}”
count = 50.to_i
output = “

Rss Reader


open(feed_url) do |http|
response = http.read
result = RSS::Parser.parse(response, false)
output += “Reed Title: #{result.channel.title}

result.items.each_with_index do |item, i|
output += “#{i+1}. ‘#{item.title}’
” if i output
end
end

You are almost done guys, now open up your views/feeds/fetch.html.erb and write a single line:

That is it. You are done.. start your server and you should see all the feeds there…
like this:

Rss Feeds

Rss Feeds

Don’t forget to drop me your inputs, suggestions, feedback on this..

With Love
Puneet

Add Default Image with Attachment_fu Plugin

Hi Guys,

Hope you all are fine and doing good. My Run Time Experiences bringing more and more posts.
Last Week I was stuck in a Big problem. I am using attachment_fu in my application. Although its a great plugin for file uploading. But I faced couple of problems like :
I m taking example of User_Profile model so there is a user_profiles table in the Db.

(1) Suppose If user left uploaded_data field blank, Next time when user updates the table value and this time also he/she left the field blank, then the Plugin shows me an error.

(2) When User left the uploaded_data field blank while creating user_profile and then try to delete his/her profile. The Plugin gives error something like this :

Can’t Convert nil to String

Now there are two ways to solve this:

(1)  Suppose your user model has_one user_profile. Then in your models/user.rb you can write something like this :

User.rb
has_one :user_profile, :dependent => :destroy

This will work for most of the cases but suppose if you want that if user has left the field blank there should be a default image which would go into the database. So for this in your model user_profile.rb write a method.

def add_default_image
self.content_type = ‘image/png’
self.filename = ‘personal-256.png’
self.temp_path = “#{RAILS_ROOT}/public/images/personal-256.png”
end

make sure that this image is present in your images folder.

Now you need to validate if params[:uploaded_data] is blank or not, suppose my action comes to create method, so do something like this :

def create
@user_profile = UserProfile.new(params[:user_profile])
if params[:user_profile][:uploaded_data].blank?
params[:uploaded_data] = @user_profile.add_default_image
@user_profile.save!
redirect_to(“Some Action”)
flash[:notice] = “Profile has been saved..”
else
if @user_profile.save
redirect_to(Some Action)
flash[:notice] = “Your contact has been saved successfully”
else
render :action => ‘new’
flash[:error] = “There is some problem saving the user”
end
end
end

Your Image should appear to you even if you left the params of uploaded_data blank. I think basics of attachment_fu you all can handle.

Cheers :)

Problem in Installing Contacts GEM in Windows

hey guys,
In this post of mine, I will show you how to install ‘contacts’ gem in your windows machine.

God, I searched google a lot for this and at last I found something interesting which I want to tell you.

I was working on linux, I switched to windows recently. During my project I thought to install contacts which will import my contacts from Gmail, Yahoo and Hotmail. When I write in command prompt:
C:\> gem install contacts

it gives me the following error

nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6
for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6/ext/gem_make.out

I think lots of you have seen this kind of error, Now I am telling you the steps how to solve this
Concentrate on line this :

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6

Now go to this Url
http://rubyforge.org/frs/?group_id=1028
and install the latest ferret gem having mswin32 version. Install it and run it, I think all of you know how to install gem manually :)

Then try to install contacts gem, It will run.
Just in case if it gives error again like this:

nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3 for
inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3/ext/json/ext/parser/
gem_make.out

Then go to this url:
http://rubyforge.org/frs/?group_id=953
and download the latest mswin32 gem of json and install it. After installing it try to run

gem install contacts

Your gem should install.

Generate XML with Rails

Hello All,
Happy New Year in Advance, In this post of mine, I will generate XML with Buildergem. Here is how to do this:
go to terminal, in my case I m generating a new application.
–> rails myapp
go into the directory and type
–> mysql -u root -p
This will open mysql query browser in the terminal itself, create a new schema
–> create schema myapp_development;
type –> exit and get out from terminal, open your –> database.yml and change it according to that.
Now, generate a model Address by this:
–> ruby script/generate model Address
now open your addresses.rb from db/migrate folder and add following lines
–> t.string :name
t.string :city
One thing to be noted here, I m using acts_as_authenticated plugin, so I have added user_id also in that, so that It will be easy for me to generate XML for the current_user i.e the logged in user.
run –> rake db:migrate
if you have builder gem installed open up environment.rb file from config folder and add
–> require ‘builder’
after the end the ‘end’ line.
If you don’t have builder, you can easily install it by typing
–> sudo gem install builder
I think you guys are able to generate rhtml pages of it, now let’s see the controller action:
–> def new
@address = Address.new
end

screenshot

from here my action goes to generate, see how gen_xml will store data.

–> def generate
@address = Address.new(params[:address])
@address.user_id = current_user.id
if @address.save
redirect_to :action => ‘gen_xml’
end
end
values of address are saved, let’s see our new action i.e gen_xml

–> def gen_xml
@xml = Builder::XmlMarkup.new
@addresses = Address.find(:all, :conditions => ["user_id = ?", current_user.id])
render :layout => false
end
Here Builder is your gem and it will generate XmlMarkup, here I m giving render :layout => false, coz I want to display generated XML without any CSS. Now your next step will be to create a file in your controller name gen_xml.rxml and add the below code:

–> xml.instruct! :x ml, :version=>”1.0″
xml.declare! :D OCTYPE, :html, :P UBLIC, “-//W3C//DTD XHTML 1.0 Strict//EN”, “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”

xml.addresses{
for address in @addresses
xml.address do
xml.name(address.name)
xml.city(address.city)
end
end
}
that’s it you are done, below is the screenshot of what I have done:

screenshot-2

If you find any problem or if you have done it successfully, please leave a comment. It will give boost up my confidence level.

Thanks