8
7

More than 3 years have passed since last update.

【Rails】【エラー】undefined method `to_key' for ×××

Posted at

image.png
railsにて上記エラーが発生しました。

解決法

posts_controller.rb
  def index 
    @posts = Post.all
  end
index.html.erb
  <%= form_for @posts ,html: { class: "form-group" } do |form| %>

@posts = Post.allで定義しているインスタンス変数に対してform_forを使っていたため、form_forを使用しない構成にしました。

原因

■ ActiveRecord::Relationを返すメソッド
all
scope (実装でnilを返すとallと同様になる)
select (使い方次第)
group
order
reorder
unscope
from
:
(省略)
:

■ 配列やオブジェクトを返すメソッド
select (使い方次第)
find
find_by
take
first
last
second
third
fourth
fifth
:
(省略)
:

メソッドにはActiveRecord::Relationを返すものと配列やオブジェクトを返すメソッドと種類があり、form_forの対象であるモデルをallであるActiveRecord::Relationを返すメソッドを使用していたためにエラーが発生したものと思われます。

8
7
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
8
7