如何在 Rails 模型上构建 Ruby?

How to structure a Ruby on Rails model?

在我们应用的用户模型中,我们已经拥有:

attr_accessor :remember_token, :activation_token, :reset_token
  before_save   :downcase_email
  before_create :create_activation_digest
    before_save { self.email = email.downcase }
    validates :first_name, presence: true, length: { maximum: 50 }
    validates :last_name, presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                        format: { with: VALID_EMAIL_REGEX },
                        uniqueness: { case_sensitive: false }
    has_secure_password
    validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

现在,我们需要给模型添加关系关联,即:

has_many :roles, dependent: :destroy
has_many :agendas, through: :roles

我们在模型中将后者包含在前者之前还是之后是否重要?

如果是,推荐/首选/最佳方式是什么?

没关系,重要的是要始终如一。通常的最佳做法是首先尽你所能声明 class' 结构,然后再进入任何操作细节。例如:

class User < ActiveRecord::Base
  attr_accessor :remember_token, :activation_token, :reset_token

  has_many :roles, dependent: :destroy
  has_many :agendas, through: :roles

  before_save   :downcase_email
  before_create :create_activation_digest
  before_save { self.email = email.downcase }
  validates :first_name, presence: true, length: { maximum: 50 }
  validates :last_name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
end

同样,这只是一种做事方式,但它在 Rails 个应用程序中很常见。