Search code examples
ruby-on-railsrubydatabaserecord

Insert a record with "find_or_create_by" inside another controller fails


This is my code:

class ApplicationsController < ApplicationController

def new
    @application = Application.new
end

def create
    @application = Application.new(application_params)
    @layout = Layout.find_or_create_by(application_id: @application.id)

    if @application.save
        redirect_to @application
    else
        render 'new'
    end
end

layout belongs_to :application

When I check the Layouts table it is empty. Can you help me, please?


Solution

  • Your model contains the following validations:

    validates :adv_path, presence: true 
    validates :start_time, presence: true 
    validates :end_time, presence: true
    

    Therefore you are not able to create a Layout without this values. You must do something like this (with useful values):

    Layout.find_or_create_by(id: @application.id) do |layout|
      layout.adv_path   = 'A useful default'
      layout.start_time = 1.second.ago
      layout.end_time   = 100.year.from_now
    end
    

    Or rethink the need for the validators.