Model Class
suggest changeclass Post < ActiveRecord::Base
belongs_to :user
has_many :comments
validates :user, presence: true
validates :title, presence: true, length: { in: 6..40 }
scope :topic, ->(topic) { joins(:topics).where(topics: { id: topic.id }) }
before_save :update_slug
after_create :send_welcome_email
def publish!
update(published_at: Time.current, published: true)
end
def self.find_by_slug(slug)
find_by(slug: slug)
end
private
def update_slug
self.slug = title.to_s.parameterize
end
def send_welcome_email
WelcomeMailer.welcome(self).deliver_now
end
end
Models are typically responsible for:
- setting up relationships
- validating data
- providing access to data via scopes and methods
- Performing actions around persistence of data.
At the highest level, models describe domain concepts and manage their persistence. title.join is not a String method. parameterize builds the slug. The :topic scope expects a topic record and filters the joined topics table.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents