前提・実現したいこと
2つのレコードを同時登録をしたいのですがうまくいきません。
複数レコードを登録する際にエラーが出ます。
ActiveRecord::RecordInvalid (Validation failed: Directions recipe must exist):
5時間以上かけて解決しようと色々と調べているのですが解決しません。ご協力よろしくお願いします!!!
model
ruby
1class Recipe < ApplicationRecord 2 has_many :directions, -> { order("number ASC") }, dependent: :destroy 3 accepts_nested_attributes_for :directions 4 belongs_to :user 5end 6 7class Direction < ApplicationRecord 8 belongs_to :recipe 9 validates :recipe_id, presence: true 10 validates :number, presence: true 11 validates :content, presence: true 12end 13 14class User < ApplicationRecord 15 has_many :recipes 16 before_save { self.email = email.downcase } 17 validates :name, presence: true, length: { maximum: 50 } 18 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(.[a-z\d\-]+)*.[a-z]+\z/i 19 validates :email, presence: true, length: { maximum: 255 }, 20 format: { with: VALID_EMAIL_REGEX }, 21 uniqueness: { case_sensitive: false } 22 has_secure_password 23 validates :password, presence: true, length: { minimum: 6 } 24end
View
html
1<% provide(:title, 'Create Recipe') %> 2<h1>レシピを作成する</h1> 3<div class="row"> 4 <div class="col-md-6 col-md-offset-3"> 5 <%= form_for @recipe do |f| %> 6 <%= f.label :name %> 7 <%= f.text_field :name, class: 'form-control' %> 8 <%= f.label :description %> 9 <%= f.text_field :description, class: 'form-control' %> 10 <%= f.fields_for(:directions) do |d| %> 11 <%= d.label :number %> 12 <%= d.number_field :number %> 13 <%= d.label :content %> 14 <%= d.text_field :content %> 15 <% end %> 16 <%= f.submit "Create Recipe", class: "btn btn-primary" %> 17 <% end %> 18 </div> 19</div>
Controller
ruby
1class RecipesController < ApplicationController 2 3 def new 4 @recipe = Recipe.new 5 @recipe.directions.build 6 end 7 8 def create 9 @recipe = current_user.recipes.build(recipe_params) 10 @recipe.save! 11 redirect_to root_path 12 end 13 14 private 15 16 def recipe_params 17 params.require(:recipe).permit(:name, :description, directions_attributes: [:number, :content]) 18 end 19end
環境
- Docker version 18.09.2
- docker-compose version 1.23.2
- ruby 2.5.5
- Rails 5.2.3
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。