[RAILS] ActiveModel is convenient when creating Form class

Previously, I wrote an article to create a Form class with the title "Virtus is convenient". At this time, I was using Virtus, but if it is Rails 5.2 or later, only ActiveModel is required. To be precise, use ActiveModel :: Attributes

class ConstructionsSearchForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :building_name,    :string
  attribute :sales_staff_id,   :integer
  attribute :department_id,    :integer
  
  ....(Omitted)

  def search
    Construction.ransack(
      building_name_cont: building_name,
      sales_staff_id_eq: sales_staff_id,
      sales_staff_department_id_eq: department_id,
    ).result
  end 
end

Create a Form class as above and use controller

@constructions = ConstructionsSearchForm.new(search_params).search

Just call. It's easy! !!

When you want to add validation etc., as in the last time, ActiveModel :: Model is included, so

  attribute :building_name,    :string
  attribute :sales_staff_id,   :integer
  attribute :department_id,    :integer

  validate :building_name, presence: true

Just write it for the same as ActiveRecord and validate it with .valid?. The types that can be specified with ActiveModel :: Attributes are described in here.

Recommended Posts

ActiveModel is convenient when creating Form class
JUnit 5 parameterization test is super convenient
ActiveModel is convenient when creating Form class
10⁹⁹⁴²⁰⁶⁷ is 8 digits
When the bean class name is duplicated
% rails db: When creating, the LoadError caused by mimemagic is
Delegate is convenient to use when you want to reuse parts