【问题标题】:Validation failed: Model1 model2 must exist验证失败:模型 1 模型 2 必须存在
【发布时间】:2017-08-26 20:56:45
【问题描述】:

我正在尝试通过模型 Survey 和 UserPair 的嵌套表单创建 has_one/belongs_to 关系。但是,在保存!时,它会引发错误,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

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 谢谢!经过一番挫折,我在您回答之前大约一个小时就想到了这一点。
    猜你喜欢
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多