Monday, August 25, 2008

NAMED_SCOPE in Ruby on Rails

The has_finder gem has been added to Rails with a different name: named_scope

For better understand let go through the following example:

class Article < ActiveRecord :: Base
named_scope :published, :conditions => {:published => true}

named_scope :containing_the_letter_c, :conditions => "author LIKE '%c%’"
end

Article.published.paginate(:page => 1)
Article.published.containing_the_letter_c.count
Article.containing_the_letter_c.find(:first)

Instead of creating a new method named published to return all published posts, I'm using a named_scope to do it for me.
But it can go even further than this. Let's look at another example of how it can be used:


named_scope :written_before, lambda { |time|
{ :conditions => ['written_on < ?', time] }
}

Search from multiple tables in mysql

CREATE TABLE `tagsearch`.`books` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(200) NOT NULL,
`author` varchar(100) NOT NULL,
`price` float(10,2) NOT NULL,
`comment` text,
`created_on` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`updated_on` timestamp NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)

CREATE TABLE `tagsearch`.`tags` (
`id` int(11) NOT NULL auto_increment,
`tagname` varchar(200) NOT NULL,
`counter` int(10) NOT NULL default '0',
`created_on` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`updated_on` timestamp NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)

Suppose we have in database these two tables.... and search query is as below.....

select * from books,tags WHERE MATCH(author,comment,tagname) AGAINST ('rails' in boolean mode);

Here, keyword is search from two tables and Match includes the field name of different table and against have search keyword

Contact Me for any help regarding rails/nodejs/php/mysql

Name

Email *

Message *