0
2

More than 3 years have passed since last update.

accepts_nested_attributes_forとfields_forを使ってデータを保存で苦戦した(has_one とbelongs_to 使用)

Posted at

環境 rails 5.2.3 ,ruby 2.5.1

問題点

taskの内容は保存されるのにdaytimeのデータは全く保存されない!

model task

class Task < ApplicationRecord
has_one :daytime
accepts_nested_attributes_for :daytime
end

model daytime

class Daytime < ApplicationRecord
belongs_to :task ,optional: true
end

改善点 tasks_controller.rb

  • before
    def new
    @task = Task.new
    @task.daytimes.new
    end

  • after
    def new
    @task = Task.new
    @task.build_daytime
    end

@task.daytimes.newだと
undefined method `new' for nil:NilClassとエラーが出ていたので
@task.build_daytimeにしたら出なくなった

また、ストロングパラメータも
daytime_attributes:とする!
daytimes_attributes:ではない!

改善点2 views/tasks/new.html.haml

= f.fields_for :daytime do |i|
とする!

= f.fields_for :daytimes do |i|
ではない!

まとめ

has_oneはあまりつかったことがなく、いつもhas_many ばかり使っていたため
複数形、単数系の違いでものすごくエラーにハマった!
has_oneの場合は単数系であることを意識していこう!
にしてもどうして
@task.daytimes.newの表記ではダメなのかは分からなかった。
ちなみにnew→buildにしてもdaytimes→daytimeにしてもこの表記はだめだった。。。

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