Tuesday 25 September 2012

Solution: Make Use of Rails Serialization

Solution: Make Use of Rails Serialization


There are some important topic

  • Never build beyond the application requirements at the time you are writing the code.
  • If you do not have concrete requirements, don't write any code.
  • Don't jump to a model prematurely; there are often simple ways, such as using Booleans and denormalization, to avoid using adding additional models.
  • If there is no user interface for adding, removing, or managing data, there is no need for a model. A denormalized column populated by a hash or array of possible values is fine.










Figure : A form that enables a user to select multiple values for an item, including other.

Above figure, shows a registration form where the user is asked to select the one or more ways he/she heard about the organization. A user who selects Other should fill in the "other" text input field. This is a fairly common interface, and you can model it in a few different ways, using Active Record models.

"Has" and "Belongs to Many"
The first way to model the user interface shown in figure is to normalize the possible "heard about" values into a referral model that is related to the user  with a "has and belongs to many" relationship:

class Referral < ActiveRecord::Base
  has_and_belongs_to_many :users
end

In, addition, User has a string attribute, referral_other, that stores the value typed into the "other" input field.

"Has Many"
The second way to model the user interface shown in the figure would be to not join the User and Referral models together with a "has many" relationship and not normalize the content of the Referral model. The model code for this would look as follows:

class User < ActiveRecord::Base
  has_many :referral_types
end

class Referral < ActiveRecord::Base
  VALUES = ['Newsletter','School','Web','Partners/Events','Media','Other']
  validates :value, :inclusion => {:in => VALUES}

  belongs_to :user
end

In addition, the User model would once again have a string attribute, referral_other, used for storing the value typed into the "other" input field.


No comments:

Post a Comment