Wednesday, February 3, 2010
Getting data with has_many and belongs_to associations
id Integer Auto-incrementing field
title Varchar(255)
description text
Tasks Table
id Integer Auto-incrementing field
name Varchar(255)
comment text
project_id Integer #This tells which project a task belongs to. This field is named following a Rails convention and refers to a related row in the projects table. This is called a foreign key and is more than just a device to help a programmer remember table and object relationships.
Project Model (project.rb)
has_many :tasks
Task Model (task.rb)
belongs_to :project
For instance, from the relationships defined in the models each task has a project title that can be accessed by task.project.title and each project has a list of tasks accessed by project.tasks.
An example shows the ease of finding all the tasks for a specific project.
def show
project = Projects.find(params[:id])
tasks = project.tasks.find(:all)
end
This example is similar to the list action above. The "1" in the URL below is where params[:id] comes from.
http://www.somesite.com/projects/show/1
Downloading files in Ruby on Rails
before_filter :login_required
def download
send_file '/home/railsway/downloads/huge.zip', :type=>"application/zip"
end
Apache server needs one extra header called XSend file to download the file. so Use below in case of that.
before_filter :login_required
def download
send_file '/home/railsway/downloads/huge.zip', :type=>"application/zip", :x_sendfile=>true
end
Ruby on Rails File Column plugin usage
In model
class Product < ActiveRecord::Base
file_column :image #image is the field name in db for Products table
end
Generate browse button in view
<%= file_column_field “product”, “image” %>
and display uploaded images in your view:
<%= image_tag url_for_file_column(“product”, “image”) %>
However, you may want to protect against the model object having no uploaded image:
<%= image_tag url_for_file_column(“product”, “image”) if @product.image %>
To resize every uploaded image to a maximum size of 640×480, you just have to declare an additional option.
class Product < ActiveRecord::Base
file_column :image, :magick => { :geometry => “640×480>” }
end
You can even automatically create versions in different sizes that have nice filenames…
class Product < ActiveRecord::Base
file_column :image, :magick => {
:versions => { “thumb” => “50×50″, “medium” => “640×480>” }
}
end
and display them in your view:
<%= image_tag url_for_file_column(“image”, “entry”) %>
Tuesday, February 2, 2010
Whats new in PHP5
Joins in mysql
Join, left join, right join, inner join, outer join
Here i explained each one by taking two tables as an example.
mysql>Products Table;
+----+--------------+--------------+
| id | product_name | manufacturer |
+----+--------------+--------------+
| 1 | Shoes | Company1 |
| 2 | Laptop | Company2 |
| 3 | Monitor | Company3 |
| 4 | DVD | Company4 |
+----+--------------+--------------+
4 rows in set (0.00 sec)
Table buyers:
mysql> SELECT * FROM buyers;
+----+------+------------+----------+
| id | pid | buyer_name | quantity |
+----+------+------------+----------+
| 1 | 1 | Steve | 2 |
| 2 | 2 | John | 1 |
| 3 | 3 | Larry | 1 |
| 4 | 3 | Michael | 5 |
| 5 | NULL | Steven | NULL |
+----+------+------------+----------+
5 rows in set (0.00 sec)
Normal Join
mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s join products on buyers.pid=products.id;
(OR)
mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s,products WHERE buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
4 rows in set (0.00 sec)
The above query displays results only with matching pids in both tables.
Left Join
mysql> SELECT buyer_name, quantity, product_name FROM buyers LEFT JOIN products ON
buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
| Steven | NULL | NULL |
+------------+----------+--------------+
5 rows in set (0.00 sec)
Explaination:
Mysql starts with the left table (buyers) as main source then For each row from the table buyers mysql scans the table products with pid (i.e id of the product in products table) and returns the product name. Then the product name is joined with the matching row to the table buyers. For unmatched rows it returns null.
The above query is same as below (except with null values)
mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s,products WHERE buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
4 rows in set (0.00 sec)
The above query displays results for only matching pids in both tables.
Right Join
mysql> SELECT buyer_name, quantity, product_name FROM buyers RIGHT JOIN products ON
buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
| NULL | NULL | DVD |
+------------+----------+--------------+
5 rows in set (0.00 sec)
Explaination:
Mysql starts with the Right table (products) as main source then For each row from the table products mysql scans the table buyers with id (i.e pid of the buyers table) and returns the product name. Then the product name is joined with the matching row to the table products. For unmatched rows it returns null. From my example above it returns NULL for DVD because no one bought DVD.
Inner join is same as join.
The word OUTER may be added after the word LEFT or RIGHT in the left/right joins - it's provided for ODBC compatibility and doesn't add an extra capabilities.
Sql Difference between where clause and Having clause
1. Having clause is usually used with Group By clause although it can be used without it too.
2. 'Having' is just an additional filter to 'Where' clause.
3. 'Where' clause applies to the individual rows whereas 'Having' clause is used to test some condition on the group(usually aggregate methods) rather than on individual rows.
4. WHERE clause is used to impose condition on SELECT statement as well as single row function and is used before GROUP BY clause where as HAVING clause is used to impose condition on GROUP Function and is used after GROUP BY clause in the query. For example queries look at http://www.allinterview.com/showanswers/6252.html
Monday, February 1, 2010
Awesome rounded cornered blocks using CSS only - nifty corners
To display rounded cornered block in your webpage, most probably we are designing rounded cornered blocks in photoshop then converted the image using css by taking small corner images as source for displaying rounded corner effect, But we can do this by using only css not any images or javascript support needed. The concept is called nifty corners see the demo http://acko.net/files/nifty-aa.html
You can earn money while visitors leaving your website
Hide default navbar menu and search from your blog
1. Login to Blogger then klick "Layout --> Edit HTML".
2. Copy the code below and insert into your tag styles section.
#navbar-iframe {
display: none !important;
}
Good Luck., happy bloging
Friday, January 29, 2010
Awesome Taxonomy module for categorise content in drupal
A small Tip
["foo", "bar"].each do |method|
MyClass.send(method)
end
The above code is same as calling MyClass.foo and MyClass.bar.
Make your rails application DRY with constants
One of the ways I utitilise constants is to standardise the date formatting I use across an app.
For example, in environment.rb I will create a module to contain my date format constants:
module Dates
DATE_FORMAT = "%d% %b %Y"
DATE_TIME_FORMAT = "#{DATE_FORMAT} %H:%M"
end
The module just groups them nicely together. To use the constants I will write the following:
@object.created_at.strftime(Dates::DATE_FORMAT)
@object.created_at.strftime(Dates::DATE_TIME_FORMAT)
Remember you will need to restart your server after making any changes to environment.rb
Helpers usage in ROR
Using helpers is simple, each controller has it's own helper file or you can write helpers in the application helper file if it will be used across the entire application. For example a pagination helper might go in there.
def my_helper(opts={}) #args defined as hash
"output something" if opts[:method_passed_in] == "foo"
end
You can then use it in your view with:
<%= my_helper('foo') %>
Ruby on Rails User multiple layouts in single controller
layout :choose_layout
private
def choose_layout
if [ 'signup', 'login' ].include? action_name
'login'
else
'admin'
end
end
Alternate row colors for table rows in Ruby on Rails
<%- for item in @items do -%>
tr class="<%= cycle("even", "odd") %>"
... use item ...
/tr
<%- end -%>
Then in your stylesheet add below
tr.even td{
background-color:#CCC;
}
tr.odd td{
background-color:#EEE;
}
Thursday, January 28, 2010
Solution to Undefined method `cache_template_extensions=' in Ruby on Rails
the below error
Undefined method 'cache_template_extensions='
To fix this problem check your environment.rb and environemts/development.rb, production.rb, test.rb files and comment/remove the below line of code.
config.action_view.cache_template_extensions = false
Restart the server and see output.
Solution to uninitialized constant FileColumn::ClassMethods::Inflector in Ruby on Rails
my_options = FileColumn::init_options(options,
ActiveSupport::Inflector.underscore(self.name).to_s,
attr.to_s)
Also at line number 79 find and change as below
url << size="4">Restart the server and see the output.
Wednesday, January 20, 2010
Solution to Google checkout payment gateway oops error
by login with your merchant details then Goto
Tools -> Integrated console
There you can see the log of what problems occured while users try to pay you.
Linux chage folder permision to a group
Hi, In linux root have the full permission over entire os and other users will have some previliages only. So when you loggin to the system and want to have write permission to one folder all you have to do, first see the permission of that folder, it contains three blocks,
OWNER - root
GROUP - root
OTHERS --
Here this means all all writes are permitted to root only. If you want to have write permission to this folder, First change the group permission to your group, then provide the write permission to the group. For this follow the below commands
First login as superuser that i.e root for this run command 'su' in the terminal
sudo su
enter root password:
chgrp -R venkat /var/www
#the above command will change the group
chmod -R g+w /var/www
#the above command will provide the write permission to the group
Now the user who logged in as venkat can have the read write permission to the folder var/www
r = read permission
w = write permission
x = execute permission
- = no permission
Ref: http://www.tuxfiles.org/linuxhelp/filepermissions.html
http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html
Tuesday, January 19, 2010
Remove N/A option for radio buttons and select boxes in Drupal using CCK
if (!$field['required']) {
if ((in_array($field['widget']['type'], array('optionwidgets_buttons', 'nodereference_buttons', 'userreference_buttons')) && !$field['multiple'])
|| (in_array($field['widget']['type'], array('optionwidgets_select', 'nodereference_select', 'userreference_select')))) {
$options = array('' => theme('optionwidgets_none', $field)) + $options;
}
}
Now the N/A option is not displayed for radio buttons and select boxes.