Wednesday, December 8, 2010

Single table inheritance

Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end

When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(:name => '37signals').first and it will return a Firm object.

If you don’t have a type column defined in your table, single-table inheritance won’t be triggered. In that case, it’ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

Thursday, September 9, 2010

RoR FAQ's

RUBY

1. Why RUBY?

2. Different type of variables in RUBY?

3. What is 'class' and 'module'

4. class methods vs instance methods

5. Singleton instance methods?

6. What is send method in RUBY?

7. How constructor can be create in RUBY?

8. What is inheritance how ruby supports inheritance?

9. include vs extend?

10. HOw can we call super class method from sub class?

11. what is super and how it will work?

12. proc vs block?

13. Can we extend more than one class from a Ruby class?

14. In Ruby how
method_missing
and
undefined method
can handled?

15. What is eval mention types of evals?

16. How Garbage collection handled in Ruby?

17. Ruby Symbol vs String?

18. In ruby how methods can be dynamically defined?

19. What is lambda?

20. What is meta programming?



Rails

21. Why RoR?

22. How is Rails DRY?

23. What are migrations?

24. what are associations, types of association?

25. How can we manually set the table name in model?

26. How can we manually set the primary_key in model?

27. How polymorphic association work in ROR?

28. In HABTM how can set the join table manually?

29. ActiveRecord's find vs find_by_xxxx

30. nil.id returns?

31. update_attribute vs update_attributes?

32. what is attr_accessor?



Some of the solution can find from my blog and puneeth's blog.

http://puneetitengineer.wordpress.com/2008/10/03/ruby-on-rails-interview-questions/#comment-306.

Feel free to add some more questions!!

Sunday, September 5, 2010

load vs require

Load

To load a file we use the load method:

load ‘blah.rb’

Note that we must supply the extension when we use it. When Ruby encounters a load, it will read in the contents of the file you’re trying to load. It will do this every time. No matter how many times you load the same feature, Ruby will read the file in every time it encounters a load. You’re not limited to just supplying a name and extension though, you can navigate directories e.g.:

load ‘../../blah.rb’

or even give an absolute path:

load ‘/a/b/c/blah.rb’


Require

No matter how many times you require the same feature in your program, only the first time is significant. Ruby will not re-read a file a second time, this is the first fundamental difference from how load works. The other obvious difference is the fact that you don’t need to supply an extension when you require a feature:

require ‘blah’

Friday, August 27, 2010

Ruby: Dynamically Define Method

http://blog.jayfields.com/2008/02/ruby-dynamically-define-method.html

Thursday, July 29, 2010

Wednesday, July 21, 2010

Search BY first name or last name or canacatination of first name and last name

named_scope :username_like, lambda { |value| {:conditions => ["first_name LIKE ? OR last_name LIKE ? OR CONCAT(first_name,' ',last_name) LIKE ?",value,value,value]} }

Friday, June 25, 2010

Wednesday, June 16, 2010

Select/Un Select check boxes with javascript

view:

<%=check_box_tag :id => "select_all" %>

User List
<% @users.each do |user| %>
<%=check_box_tag "recipient[]", :value => "user.email" %>
<% end %>


javascript code:

script type ="text/javascript">
$(function(){
$("#select_all").click(function(){
$flag = $(this).attr('checked');
if ($flag) {
$("input[name='recipient[]']").each(function(){
$(this).attr('checked', true)
});
}else{
$("input[name='recipient[]']").each(function(){
$(this).attr('checked', false)
});
}
});
});

Rails dynamic layout selection

controller:
class MyController < ApplicationController
layout :check_layout




private

def check_layout
return current_user.admin? ? "admin" : "application"
# current_user is user who logged in
end


end

Monday, June 7, 2010

Multiple Ruby versions in Windows

Multiple ruby versions in windows can possible with "http://github.com/vertiginous/pik">Pik

Install gem gem install pik;

After the gem is installed, you can use the ‘pik_install’ script to install the pik executable. Install pik to a location that’s in your path, but someplace other than your ruby\bin dir.

Path
For instance, the directory C:\Pik is in my path:

Set the path in 'Environment variables' like
>path PATH=C:\Pik;C:\Program Files\Windows Resource Kits\Tools\;c:\ruby\Ruby-186-p383\bin;

Saturday, March 13, 2010

gem vs plugin

Rails Plugins

Rails plugins are pieces of code that can be added to a Rails application on at the application level, and reside in the vendor/plugins folder of that application. Plugins are simple to install by simply typing:

syntax
script/plugin install plugin_name

from within the root directory or a Rails application. The main feature to plugins is that they install in each application, and are specific to that application.

Ruby Gems
Ruby gems are also pieces of ruby code that can be added to a system running Ruby, just as simply as adding plugins to an application:

syntax
gem install gem_name

However, gems are installed at a system level, which means that rather than being specific to a Rails application, like a plugin is, gems are available to all Rails applications that are running on the same system. In other words, you would install a gem on your web server, where it is available to all Rails applications running on that web server.

REST vs. CRUD

REpresentational State Transfer and describes resources (in our case URLs) on which we can perform actions. CRUD, which stands for Create, Read, Update, Delete, are the actions that we perform. Although, in Rails, REST and CRUD are bestest buddies, the two can work fine on their own. In fact, every time you have written a backend system that allows you to add, edit and delete items from the database, and a frontend that allows you to view those items, you have been working with CRUD.

Resources

You would be used to seeing Rails URLs that look something like /posts/view/2 – which roughly translates to “Please let me view the post with the id number 2″. RESTful resources are very similar, in that they have a controller and (maybe) and id. What they generally don’t have is an action, because it is inherent in the HTTP verb.

To make this work, the Rails team have defined a number of special methods in the controllers that define resources – in this case posts (the .xml bit will become clear in the next part).

Method Resource Verb Explanation
index /posts.xml GET Returns all items
show /posts/1.xml GET Return a single item with id = 1
create /posts.xml POST Create an item
update /posts/1.xml PUT Update item with id = 1
delete /posts/1.xml DELETE Delete item with id = 1

Wednesday, March 10, 2010

Ruby on Rails: Custom primary key in ActiveRecord

Replacing the default integer-based primary keys in model with a Custom primary-key.

The solution is to disable the id column and create a customized primary key column instead.

create_table :posts, :id => false do |t|
t.string :post_id, :limit => 36, :primary => true
end

In your Post model you should then set the name of this new primary key column.

class Post < ActiveRecord::Base
set_primary_key "uuid"
end

Rails MVC

The Model is the application object, the View is its screen presentation, and the controller defines the way the user interface react to user input. Before MVC, user interface designs tended to lump these objects together. MVC uncouples them to increase flexibility and reuse.

The browser makes a request

The web server (mongrel, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb.

Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”.

Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting.

Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what happens in the back room.

HABTM Custom Join Table in RoR

has_and_belongs_to_many(association_id, options = {}, &extension) public
Specifies a many-to-many relationship with another class. This associates two classes via an intermediate join table. Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the custom :join_table option if you need to.

The join table should not have a primary key or a model associated with it. You must manually generate the join table with a migration such as this:

class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
def self.up
create_table :developers_projects, :id => false do |t|
t.integer :developer_id
t.integer :project_id
end
end

def self.down
drop_table :developers_projects
end
end

Custom Join Table Example

For Products and Categories default join table in lexical order is
categories_products.

if we want to use custom join table (prod_cats) than use 'join_table' option

class Products < ActiveRecord::Base
has_and_belongs_to_many :categories, :join_table => :prod_cats
end

class Categories < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :prod_cats
end