user2706191
user2706191

Reputation: 353

Validation failed: Model1 model2 must exist

I'm attempting to create a has_one/belongs_to relationship through a nested form for the models Survey and UserPair. However, on save!, it throws the error, Validation failed: User pair survey must exist.

The parameters output in the console upon submit are all right, but the survey_id is apparently not getting assigned to survey.user_pair.

parameters output

Parameters: {"utf8"=>"✓", "authenticity_token"=>"bPBK5aTntfnb6WSEv2VchUgETwH1nmGTWDOJJkfniLoKwBSKY1C6xoZ6Z3chQouLb6G8161T/d0AMzn4VXX0Lw==", "survey"=>{"user_pair_attributes"=>{"user1_name"=>"A", "user1_field"=>"def", "user2_name"=>"B", "user2_field"=>"abc"}, "category_ids"=>["", "1", "2"]}, "commit"=>"Start Survey"}

controllers/surveys_controller.rb

class SurveysController < ApplicationController
  def new
    @survey = Survey.new
    @survey.build_user_pair
  end

  def create
    @survey = Survey.new(survey_params)
    puts @survey.save! // trying to debug validation errors
    if @survey.save
      flash[:success] = "Survey submitted"
      redirect_to @survey
    else
      render 'new'
    end
  end

  private

  def survey_params
    params.require(:survey).permit(category_ids: [], user_pair_attributes: [:user1_name, :user1_field, :user2_name, :user2_field])
  end
end

models/survey.rb

class Survey < ApplicationRecord
  has_secure_token

  has_one :user_pair, dependent: :destroy
  has_many :users, through: :userpair, class_name: 'UserPair'

  accepts_nested_attributes_for :user_pair
end

models/user_pair.rb

class UserPair < ApplicationRecord
  belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
  belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
  belongs_to :survey
end

db/migrations/create_surveys.rb

class CreateSurveys < ActiveRecord::Migration[5.0]
  def change
    create_table :surveys do |t|
      t.string :token
      t.string :category_ids, array: true, default: []
      t.timestamps
    end
  end
end

db/migrations/create_user_pairs

class CreateUserPairs < ActiveRecord::Migration[5.0]
  def change
    create_table :user_pairs do |t|
      # Relationships
      t.belongs_to :user1
      t.belongs_to :user2
      t.belongs_to :survey, foreign_key: true

      # User1 info
      t.string :user1_name
      t.string :user1_field

      # User2 info
      t.string :user2_name
      t.string :user2_field

      t.timestamps
    end
  end
end

Upvotes: 0

Views: 623

Answers (1)

alanpaivaa
alanpaivaa

Reputation: 2089

Try this out:

class UserPair < ActiveRecord::Base
    belongs_to :user1, class_name: 'User', primary_key: 'user1_id', optional: true
    belongs_to :user2, class_name: 'User', primary_key: 'user2_id', optional: true
    belongs_to :survey, optional: true
end

Upvotes: 1

Related Questions