Wednesday, February 3, 2010

Getting data with has_many and belongs_to associations

Projects Table
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

In rails there is default method avaialable to donwload the files by users. i.e send_file. So below code will provide the user to download the file 'home/railsway/downloads/huge.zip' if (s)he logged in.

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

After installing the plugin, you should observe the below steps
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”) %>