Veerasundaravel's Ruby on Rails Weblog

February 1, 2011

Rails ActiveRecord: validate single attribute


 

In Rails ActiveRecord we can validate a whole object, but we cannot validate a particular attribute of the object something like below:

>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid?(:email)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):2:in `valid?'
from (irb):2
>>

 

Here some quick solution for validating a particular attribute of an ActiveRecord object. Create a .rb file like below place in config\initializers folder.

module ValidateAttribute
  def self.included(base)
    base.send :include, InstanceMethods
  end

  module InstanceMethods
    def valid_attribute?(attribute_name)
      self.valid?
      self.errors[attribute_name].blank?
    end
  end
end

ActiveRecord::Base.send(:include, ValidateAttribute) if defined?(ActiveRecord::Base 

 

Now you can validate a particular attribute of an object as follows:

>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid?(:email)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):2:in `valid?'
from (irb):2
>>
>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid_attribute?(:email)
>> false

>> u.valid_attribute?(:name)
>> true 

September 17, 2010

ActiveRecord – Tableless Model

If you want to create an ActiveRecord model without any table reference, and want to add validation for that model means, you can go with this example code.

In app/models/base_model.rb

class BaseModel < ActiveRecord::Base
def self.columns
@columns ||= [];
end

def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default,
sql_type.to_s, null)
end

# Override the save method to prevent exceptions.
def save(validate = true)
validate ? valid? : true
end
end

In app/models/post.rb

class Article < BaseModel
column :title, :string
validates_presence_of :title
end

In script/console

Loading development environment (Rails 2.2.2)
>> article = Article.new
=> #<Article title: nil>
>> article.valid?
=> false
>> article.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={“title”=>[“can’t be blank”]}, @base=#<Article title: nil>>


Reference Links:

http://stackoverflow.com/questions/315850/rails-model-without-database/
http://railscasts.com/episodes/193-tableless-model
http://agilewebdevelopment.com/plugins/activerecord_base_without_table

September 15, 2010

Rails delegate method

Filed under: Ruby On Rails — Tags: , , , , , , , , , — Veerasundaravel @ 2:36 pm

Delegation is a feature Rails introduced in it’s 2.2 version. The concept of delegation is to take some methods and send them off to another object to be processed.

Lets walk through some example:

Suppose you have a User model to save all of the registered user’s details, and also the user can have their individual profile. So the class definitions will become as follows:

class User < ActiveRecord::Base
has_one :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
end

Assume you stored fullname and address details of a particular user in profile model. So you can access the fullname of a particular user using

@user.proflie.fullname

But Delegation allows you to simplify this as follows:

class User < ActiveRecord::Base
has_one :profile
delegate :fullname, :address, :to => :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
end

Now you can directly access the user profile’s fullname and address as follows:

@user.fullname
@user.address

Delegates With Prefixes:

More even you can specify some prefix with your delegates like below:

class User < ActiveRecord::Base
has_one :profile
delegate :fullname, :address, :to => :profile, :prefix => true
delegate :phone, :email, :to => :profile, :prefix => “office”
end

And now you can access the user profile’s details as follows:

@user.profile_fullname
@user.profile_address
@user.office_phone
@user.office_email

Reference Links:

http://apidock.com/rails/Module/delegate
http://blog.wyeworks.com/2009/6/4/rails-delegate-method

Older Posts »

%d bloggers like this: