link_to with image_tag in Rails

This is very basic form tag in rails. but some time you get confused about using this tag.

How to displays a image inside link_to instead of text?

Here is answer:
<%= link_to image_tag(“/images/submit.jpg”, :border=>0), :action => ‘create’ %>

Section Option:

<%= link_to image_tag(“/images/submit.jpg”, :border=>0,:class=>’sub20′), :url =>{:controller=> ‘user’,:action=>’create’}  %>

Create XML document with Ruby on rails

XML is most popular data transfer layer. In every language we need XML parsing. In Ruby there is in build XML strong parsing support.

Create XML document with Ruby on rails

In this post I am going to cover the How to create XML file with simple Ruby code.

TIP: If you are new in Rails than follow step one or go to step two.

1. You need to install Ruby on your computer

http://www.ruby-lang.org/en/

2. Open command prompt(for windows) or console(linux)

3. Create file named CreateXML.rb and copy and paste following code

require “rexml/document”
include REXML

string = <<EOF
<xml>
<element attribute=”attr”>first XML document with ruby </element>
</xml>
EOF
doc = Document.new string

print doc

Output will be like this:

Create XML document with Ruby on rails
Create XML document with Ruby on rails

text_area tag in Rails – Issues

When you start New Rails project.  Always we used scaffolding for creating simple base for out application.

text_area tag in Rails – Issues

I used scaffolding for some methods. I got some very weird issue about tex_area tag in rails.

When i check the forms textagea fields are coming with 20 rows and 40 cols default. When i tried to change that is not changing even though CSS also.

<textarea id=”dummy_text” rows=”20″ name=”dummy_text” cols=”40″/>

After digging into rails code i got know that Rails ->Actionpack-> form_helper.rb file has default setting of textarea field.

def text_area(object_name, method, options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_text_area_tag(options)
end

We can change this also. but this is not good idea

so good idea is select our project and use find replace:

text_area to text_area_tag

This is the simplest solution.


Rich Text Editor in Rails Application

Many times you need normal CMS for your application. You want to need some pages data need to handle through CMS.

It is really very easy to Install any RTE in the Rails. There are many open source RTE available.

I used the Cross-Browser Rich Text Editor for my project.
I downloaded files from there and uploaded to my public folder. I added required CSS and JS file to my layout.

You need to add following lines to your application.html.erb file.(you will find this file in view/layout/ folder)

1. You can add that files on conditional base also. Means for that particular page.
2. Add following lines to your form
:html => { :name => ‘BlogRTE’, :onsubmit => “submitForm();”}

In to add following lines to your form;

<script language=”JavaScript” type=”text/javascript”>
<!–
function submitForm() {
updateRTEs();
return false;
}
initRTE(“/cbrte/images/”, “/cbrte/”, “”, true);
//–>
</script>
<noscript><p><b>Javascript must be enabled to use this form.</b></p></noscript>
<script language=”JavaScript” type=”text/javascript”>
<!–
//build new richTextEditor
var rte1 = new richTextEditor(‘text_content’);
rte1.html = ‘Write your thoughts here.’;
rte1.toggleSrc = true;
rte1.width = 500;
rte1.build();
//–>
</script>

You will get the text_content params in Rails.

For Edit page functionality i got error in form. So you need to this default code for all languages.
rte1.html =””;

When i used this i got an error.

But i solved this issue after some R&D and modification in code.

Use following code for Rails(Edit functionality)
rte1.html =”<%=text_content.gsub(/”/, “‘”).gsub(/\n/, ”).gsub(/\r/, ”) %>”;

this will solve your problem.

Full code: (IF YOUR CODE NOT WORKS THAN USE MY FULL CODE)

<script language=”JavaScript” type=”text/javascript”>
<!–
function submitForm() {
updateRTEs();
return false;
}
initRTE(“/cbrte/images/”, “/cbrte/”, “”, true);
//–>
</script>
<noscript><p><b>Javascript must be enabled to use this form.</b></p></noscript>
<script language=”JavaScript” type=”text/javascript”>
<!–
//build new richTextEditor
var rte1 = new richTextEditor(‘text_content’);
rte1.html = ‘Write your thoughts here.’;
rte1.toggleSrc = true;
rte1.width = 500;
rte1.build();
//–>
</script>

Rails if else statement

Here i am going to give some example of conditional statements in Rails.
Normal IF ELSE
<% if user %>
<%= user.name %>
<% else %>
Anonymous
<% end %>

Normal code for ELSIF
if var == 10
print “Variable is 10″
elsif var == “20″
print “Variable is 20″
else
print “Variable is something else”
end

Technic:
How to Put this in one line:
<%= user.name if user %> This is the simplest way.

How to use IF and ELSE statement in one line:
<%= user ? user.name : “Anonymous” %>

fetch svn project without svn files and without deleting

I worked with any technologies and languages. Many times we need some folder or codebase for your new project.
So we need to copy old project code or folder in our new project. In rails we need many plugins for our project. Some times few plugins are not getting installed in our project.

fetch svn project without svn files and without deleting

Few days back i tried to install acts_as_solr plugin in my project. I got an error. So i coppied acts_as_solr plugin from my old project and pasted in new project.

When i tried to SVN commit the files in the new project. That files started commiting to Old project.
So i need to remove all .svn folders form all the subfolders. Than only i can add all the folder to new project.

I google around for solution. I found many ways:

  • Remove the all .svn folder from all subfolder.
  • Through linux command find all .svn file and delete. (but i think this harmful)
  • SVN export – command

SVN export is the very simple and reliable way to fetch project out of svn.
In windows, using svn export is very easy.

Paperclip with Rails for image manipulation

I used the spree e-Commerce CMS for checking or R&D of Spree code. Spree is the really nice and basic tool for e-Commerce CMS.

When i was going through Spree i got to know about paperclip plugin which is used for image manipulation. Earlier i used “attachment_fu” for image manipulation and file uploading in rails projects.

How to use “Paperclip

First install perperclip plugin to your project.

Windows and Linux user can use my code. (I used this in WindowsXP and Fedora 9)

#ruby script /plugin install https://svn.thoughtbot.com/plugins/paperclip/trunk/

through this command perperclip get installed in your project folder.

Many time you need photo upload functionality for customer

Here i used Customer contoller and Customer model for this lession

First run following command

#ruby script/generate paperclip ModelName FieldName

In my case command is:

#ruby script/generate paperclip Customer customer_pic

One migration file will be created through this command. Run that migration.

In Customer model file paste this code:

class Customer < ActiveRecord::Base
# Paperclip
has_attached_file :customer_pic,
:styles => {
:thumb=> "100x100#",
:small => "150x150>" }
end

Using this command you will save three pic(photo) in your system folder.

Default upload url of peperclip is (RAILS_ROOT/public/system/…)

You can use following lines in your model file. (copy & paste this code under styles code)

:url => “/uploads/:class/:attachment/:id/:style_:basename.:extension”,
:path => “:rails_root/public/uploads/:class/:attachment/:id/:style_:basename.:extension”

I added uploads folder front on :class. That is optional you can remove also.

If you are already having forms for customer and if you want to add that to form. Just use this code in your form tag.

:html => { :multipart => true

and in from <%= f.file_field :customer_pic%>

That sit. you need to add or use following code in View

<%= image_tag @user.customer_pic.url %>

<%= image_tag @user.customer_pic.url(:thumb) %>

Paperclip Validations

Here i giving some validation for Paperclip. You need to just copy & paste in to your model where you want to use image upload.

validates_attachment_content_type :avatar, :content_type => 'image/jpeg'

validates_attachment_presence :avatar

I found this plugin is very usefull for Me. It really saves lots of time.

Basic of Rails routing -rails routes basic hack

Here I am going to focus on only basic routing technic of Rails.

If you are new in rails. Just wanted to remind you.

First go to Rails project’s “public” folder and delete or rename the index.html file. If index.html file is there then default routing will not run.

If you want Users controller’s index page as a home page of site then go for this code in routes.rb file.

map.connect ”, { :controller => ‘users’, :action => ‘index’ }

In view you can use link for home page and logo of site(basic hack)

<%= link_to(“HOME”,{:controller=>’/’}) %>


ActiveRecord-JDBC is for use with JRuby only….

Few days back when i tred to run my rails project. I got an error saying

ActiveRecord-JDBC is for use with JRuby only
jdbc-mysql is only for use with JRuby
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:76:in `establish_connection’: Please install the jdbcmysql adapter: `gem install activerecord-jdbcmysql-adapter` (no such file to load — java) (RuntimeError)
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:60:in `establish_connection’
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:55:in `establish_connection’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:417:in `initialize_database’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:141:in `process’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:113:in `send’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:113:in `run’
from /var/www/html/HOO/trunk/config/environment.rb:9
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:156:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:521:in `new_constants_in’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:156:in `require’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/commands/server.rb:84
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require’

I am using Fedora 9 as Os and mysql as database.

I read all the error than i got to know. I need to change my database.yml file.

in that file i have following text;

adapter: jdbcmysql

i changed that to:

adapter: jdbcmysql

socket: /var/lib/mysql/mysql.sock

I thoutht jruby database issue but not. the database setting is an issue.

Fixed this issue: Building native extensions. This could take a while…

I got this error when i tried to install various ruby gems on system.

I am using the Fedoa 9 as OS.  I tried a lot to fix this issue and googled lot but not found exactly solution.

later on realize some of latest software are not installed on OS that’s why i am getting these kind of error.

you need to install proper software on Fedora box.

# yum install ruby ruby-libs ruby-mode ruby-rdoc ruby-irb ruby-ri ruby-docs

#yum install gcc-c++

this is the solution.