ActiveRecord Programming Guide in Ruby on Rails _ruby topics

Source: Internet
Author: User
Tags joins readable ruby on rails


Avoid changing the default ActiveRecord (table name, primary key, etc.) unless you have a very good reason (like a database that is not under your control).
Put the macro-style approach in front of the category definition (Has_many, validates, and so on).

Preference Has_many:through is better than Has_and_belongs_to_many. Using Has_many:through allows additional attributes and validation in the join model

 # Use Has_and_belongs_to_many
  class user < ActiveRecord::Base
   has_and_belongs_to_many:groups end

  Class Group < activerecord::base
   has_and_belongs_to_many:users
  End

  # Preference mode-using Has_many:through
  class User < activerecord::base
   has_many:memberships
   has_many:groups, through:: Memberships
  End

  Class Membership < ActiveRecord::Base
   Belongs_to:user
   belongs_to:group
  End

  class Group < activerecord::base
   has_many:memberships
   has_many:users, through:: Memberships
  End

Use the new "sexy" validation.

Create an idiomatic validator file when an idiomatic validation is used more than once or when validation is a regular expression map.

  #
  class Person
   validates:email, format: {with:/^ ([^@\s]+) @ (?: [-a-z0-9]+\.) +[a-z]{2,}) $/i}
  end

  # good
  class Emailvalidator < Activemodel::eachvalidator
   def Validate_each ( Record, attribute, value)
    Record.errors[attribute] << (options[:message) | | ' is not a valid email ') unless value =~/^ ([^@\s]+) @ ((?: [-a-z0-9]+\.) +[a-z]{2,}) $/i End-
  class person
   Validates:email, email:true
  End

All of the usual validators should be placed in a shared gem.

Use named scopes (scope) freely.

 Class User < ActiveRecord::Base
   Scope:active,-> {where (active:true)}
   scope:inactive,-> {where (act Ive:false)}

   scope:with_orders,-> {joins (: Orders). Select (' Distinct (users.id) ')}
  end

Lazily Initializes a named scope wrapped in a lambda.

  # Bad
  class User < activerecord::base
   scope:active, where (active:true)
   scope:inactive, where (active: False)

   Scope:with_orders, joins (: Orders). Select (' Distinct (users.id) ')
  end

  # good
  class User < ActiveRecord::Base
   scope:active,-> {where (active:true)}
   scope:inactive,-> {where (active:false)}< C16/>scope:with_orders,-> {joins (: Orders). Select (' Distinct (users.id) ')} End
  

When a scope that is defined by a lambda and parameter becomes too complex, a better way is to build a class method for the same purpose and return a Activerecord::relation object. You can also define a more streamlined scope.

  Class User < ActiveRecord::Base
   def self.with_orders
    joins (: Orders). Select (' Distinct (users.id) ')
   End End
  

Pay attention to the behavior of the Update_attribute method. It does not run model validation (unlike update_attributes) and may screw up the model state.

Use a user-friendly web site. Displays descriptive model attributes, not just IDs, on the Web site.
There are more than one way to achieve this:

The To_param method of the overridden model. This is the way Rails uses to construct URLs for objects. The default implementation returns the record of the ID as a string. It can be overridden by another human-readable attribute.

    Class Person
     def to_param
      ' #{id} #{name} '. Parameterize
     End
    

In order to convert a value to a URL-friendly (url-friendly), the string should call parameterize. The ID of the object is to be placed at the beginning so that it can be found for the ActiveRecord find method.
* Use this friendly_id gem. It allows a human-readable URL to be created with some descriptive model attributes rather than an ID.

  Ruby
  class person
  extend Friendlyid
  friendly_id:name, use:: Slugged
  End

See the Gem document for more information about using.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.