basic rails question

  class Person < ActiveRecord::Base
    validates_uniqueness_of :user_name, :scope => :account_id
  end

my question is about the above three lines of code. by the way I'm c++ programmer and new to ruby and rails. I'm very very confused by the line: validates_... what's that? variable definition? function call? or something eles. For me, it's a weird line whithin a class definition.

Answers


It's a function call.

The function is defined in module (ActiveRecord::Validations). Modules in Ruby are objects and can have functions and variables attached to them.

You can include module and get it's members. Here it's done in your parent class: ActiveRecord::Base. If You look at it's definition it starts with something like:

module ActiveRecord
  class Base
    include ActiveRecord::Naming
    # ...
    include ActiveRecord::Validations
    #...
  end
end

There are some noticeable differences in way C++ and Ruby handles class declaration. Firstly, there is no compilation in Ruby. So class definition can be changed during runtime. And actually it's the default way of declaring a class. In other words: classes in Ruby are always open.

Secondly, class body can have any executable code. In C++ you can't invoke a function from class definition. It wouldn't make much sense. Yet in Ruby it makes, since You are able to do metaprogramming. This way you can invoke a function which constructs some members. That's writing functions which can write another functions. It can be a big productivity boost and a source of worst errors at the same time.

I'd highly recommend consulting the Ruby Metaprogramming: Declaratively Adding Methods to a Class entry.


It's a function call. You could rewrite it as validates_uniqueness_off(:user_name, :scope => :account_id). In Ruby, the convention is to ignore these parentheses. Rails gives you these class methods as part of ActiveRecord::Validations module. The rails API can give you more information about how it's defined and you can also take look at the sources to see how it's implemented. Hope that helps.


Need Your Help

grails run-app error Plugin not installed

grails run-app

I am using Grails 1.2.1 and Groovy-Grails Tool Suite 3.1.0. Before that I was used 2.5.2.RELEASE of STS. But after upgrading to Groovy-Grails Tool Suite 3.1.0, when I am trying to run the app I am

Debugging Help: C++ error

c++ debugging

I am getting this error:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.