< Back to Ruby on Rails notes

Models

What Rails models are and how they organize database data structures

In relational databases, there are several different types of relationships different models can have:

  1. has_many for when there’s several instances of another model related to one of the selected model
  2. belongs_to for when one instance of this model can belong to several other instances of another model
    • Can also have polymorphic: true set if it belongs to multiple different models. A polymorphic association must be declared in both cases to complete it, such as in this example.
  class TeachingAssistant < ActiveRecord::Base
    belongs_to :ta_duty, polymorphic: true
  end

  class SectionA < ActiveRecord::Base
    has_many :teaching_assistants, as: :ta_duty
  end

  

You can also define methods within models to better manage the data that’s returned. For example, if one column returns a boolean that needs to be turned into a related string, the function can do that:

  # In the model:
  def label
    if model.boolean "First Label" else "Second Label" end
  end

  # After calling an instance of the model:
  model_instance.label

Models use ActiveRecord to pull records from the database, and there’s several methods to use for getting it.

  Category.includes(:expenses)
    .where(expense: @type)
    .where(expenses: { created_at: @start_date..@end_date })