验证失败:Model1 model2必须存在

时间:2017-04-01 17:47:45

标签: ruby-on-rails activerecord ruby-on-rails-5

我正在尝试通过模型Survey和UserPair的嵌套表单创建has_one / belongs_to关系。但是,在save!上,它会抛出错误Validation failed: User pair survey must exist

提交时在控制台中输出的参数是正确的,但survey_id显然没有被分配到survey.user_pair

参数输出

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"}

控制器/ 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

模型/ 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

模型/ 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

分贝/迁移/ 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

分贝/迁移/ 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

1 个答案:

答案 0 :(得分:1)

试试这个:

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