LoginSignup
4
2

More than 5 years have passed since last update.

ActiveModelでform_forを利用時に発生するエラーを解決する

Last updated at Posted at 2016-06-02

はじめに

ActiveRecordを使ってフォーム画面を実装する際は、モデルに対応するDBテーブルが必要になりますが、データの永続化が不必要で対応するDBテーブルがない場合でもフォーム実装を行いたい時には、ActiveRecordではなく、ActiveModelを用います。ただ、ActiveModelでform_forを使おうとした場合にエラーでハマったので、そこの対処法をまとめます。

環境

  • Rails: 4.2.6
  • ruby: 2.3.0

エラーメッセージ

ActionView::Template::Error (undefined method `to_key' for #<Simulator:0x007fc4d96bfd00>
Did you mean?  to_query):
  • to_keyメソッドがないと言われ、エラーになります。

対処法

対応前

class Hoge
  include ActiveModel::Model

  # フォームで利用する値の定義
  attr_accessor :hoge, :fuga, :foo, :bar

  # バリデーションの定義
  validates :hoge, presence: true, length: { maximum: 50 }
  validates :fuga, presence: true
  validates :foo, presence: true
  validates :bar, presence: true
  • モデルでActiveModel::Modelをインクルードし、ActiveModelを利用できるようにしています。

対応後

class Hoge
  include ActiveModel::Model
  include ActiveModel::Conversion

  # フォームで利用する値の定義
  attr_accessor :hoge, :fuga, :foo, :bar

  # バリデーションの定義
  validates :hoge, presence: true, length: { maximum: 50 }
  validates :fuga, presence: true
  validates :foo, presence: true
  validates :bar, presence: true

  def persisted? ; false ; end
  • ActiveModel::Conversionをインクルードし、persisted?メソッドを定義します。
  • 上記をクラス内に記述することで、Railsの変換メソッド(さっきエラーになったto_keyメソッド)をそのクラスのオブジェクトに対して呼び出すことができるようになるそうです。

参考

4
2
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
4
2