1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Formクラス作る時は、ActiveModelが便利 

Posted at

以前、「Virtusが便利」というタイトルでFormクラスを作る記事を書かせていただきました。
この時は、Virtusを利用していたのですが、Rails5.2以降であれば、ActiveModelだけで済みます
正確には、ActiveModel::Attributesを使います

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

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

  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

上記のようにFormクラスを作って、controllerで

@constructions = ConstructionsSearchForm.new(search_params).search

呼び出すだけ。
簡単ですね!!

validation等を追加したい時も前回と同様、ActiveModel::Modelをincludeしているので、

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

  validate :building_name, presence: true

ActiveRecordと同じ用に書いて、.valid?で検証するだけです。
ActiveModel::Attributesで指定できる型は、こちらに書いてあります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?