Topic: 3 questions... Answer any :)

Hola Railers,
Newbie here, with 3 questions.

[Q.1]
Could a controller access more than 1 model?
user has_one address
address belongs_to user
address has_one zip

In users_controller.rb:
Can I access user.address?  How about user.address.zip? Should I add something, somewhere?


[Q.2]
I need to collect 25 pieces of data on a single form that is divided into 3 groups: login/pass, personal, credit card info. I want to Ajaxify it so that the user can enter data and save on the spot... The login/pass section should allow for sign up or logging on...  Any good tutorial/reference on this?

[Q.3]
What is self.Action? Wouldn't calling Action (without self) make a call to an action in the same class?


Thanx in advance,
James.

Re: 3 questions... Answer any :)

1) you can totally access as many different kinds of models as you want in a controller action.  Ordinarily there's a particular model that relates to a particular controller (UsersController and User model, e.g.) but that shouldn't stop you from handling any relevant models.

2) Check the tutorials section of this website.  Look for anything written by RyanB - he's amazing.

3) when a Ruby class has a method that's called self.method_name it means that the class doesn't have to be instantiated as an object for that method to be used.  Like so:

class MyClass
  def method_one
    puts 'first method!'
  end
  def self.method_two
    puts 'second method!'
  end
end
mc = MyClass.new
mc.method_one # => 'first method!'
mc.method_two # => NoMethodError: undefined method `method_two' for #<MyClass:0xb7013f08>
MyClass.method_one # => NoMethodError: undefined method `method_one' for MyClass:Class
MyClass.method_two # => 'second method!'

That's the advantage of using self rather than just naming the method.

Yay, I answered them all - did I win a cookie?

Last edited by danger (2007-01-09 03:03:48)

Re: 3 questions... Answer any :)

Amazing... Thanks a lot Danger.
And your cookie is safe with me  smile

J.

Re: 3 questions... Answer any :)

On Q.3:

If you were overloading find_by_id, would you have used self.find_by_id? i.e. is this an example of an action being called on an uninstantiated object (User)? Is self. needed?

@current_user = User.find_by_id(session[:user_id])

Re: 3 questions... Answer any :)

Yes.
All of the 'find' methods are called on the User class.  The idea is that it doesn't relate to any particular instance (or record) but rather to the class as a whole.

There are two ways to do this:

1) Overload the method on ActiveRecord::Base and change the way all records are found:
class ActiveRecord::Base
  def self.find_by_id
    # code
  end
end
2) Overload the method on just the class you want:
class User < ActiveRecord::Base
  def self.find_by_id
    # code
  end
end

Re: 3 questions... Answer any :)

Beginner question but what is overloading ?