ActiveRecord programming guide in Ruby on Rails, rubyonrails
Avoid modifying the default ActiveRecord (Table Name, primary key, and so on) unless you have a very good reason (such as a database not under your control ).
Put the macro-style method before the class definition (has_many, validates, and so on ).
Preference has_expect: through is better than has_and_belongs_to_expect. Has_validation: through allows additional attributes and verification in the join model.
# Use Authorization class User <ActiveRecord: Base has_and_belongs_to_records: groups end class Group <ActiveRecord: Base users: users end # preference-using has_records: through class User <ActiveRecord :: base has_records: memberships has_attributes: groups, through: memberships end class Membership <ActiveRecord: Base partition: user belongs_to: group end class Group <ActiveRecord: Base has_attributes: memberships has_attributes: users, through: memberships end
Use the new "sexy" validation.
When a regular verification is used more than once or the verification is a regular expression ing, a regular validator file is created.
# Difference 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 common validators should be placed in a shared gem.
Use the named scope freely ).
class User < ActiveRecord::Base scope :active, -> { where(active: true) } scope :inactive, -> { where(active: false) } scope :with_orders, -> { joins(:orders).select('distinct(users.id)') } end
Initialize the named scope package in lambda with inertia.
# Poor 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)} scope: with_orders,-> {joins (: orders ). select ('distinct (users. id) ')} end
When a scope defined by lambda and parameters becomes too complex, a better way is to create a category 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 verification (unlike update_attributes) and may mess up the model status.
Use user-friendly URLs. The URL displays descriptive model attributes, not just IDs.
There are more than one way to achieve this:
Overwrite the to_param method of the model. This is the method Rails uses to construct URLs for objects. By default, records of this id are returned in the form of strings. It can be overwritten by another human-readable attribute.
class Person def to_param "#{id} #{name}".parameterize end end
To convert the value to a URL-friendly value, the string must call parameterize. Put the Object id at the beginning to search for the find method of ActiveRecord.
* Use this friendly_id gem. It allows you to create human-readable URLs with descriptive model attributes instead of IDs.
Ruby class Person extend FriendlyId friendly_id :name, use: :slugged end
View the gem documentation.