如何仅使用我的params白名单方法在Rails中创建具有深层嵌套关联的模型对象?

时间:2018-11-19 03:01:10

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

要重复这个问题,我的基本模型是project

class Project < ApplicationRecord
  has_many :tones, as: :analyzable
  has_many :sentences
  accepts_nested_attributes_for :tones, :sentences
end

我还有另外两个模型:

class Sentence < ApplicationRecord
  belongs_to :project
  has_many :tones, as: :analyzable
  accepts_nested_attributes_for :tones
end

class Tone < ApplicationRecord
  belongs_to :analyzable, polymorphic: true
end

在我的ProjectsController中,我希望有一个create操作,该操作只接受列入白名单的参数并创建具有所有适当关联的项目。我的project_params方法如下:

private
  def project_params
    params.permit(:text, :title, :img, sentences_attributes: [:id, :text, tones_attributes: [:score, :tone_name]], tones_attributes: [:id, :score, :tone_name])
  end

但是,如果我尝试以下操作:

project = Project.create(project_params)

我将收到以下错误:

| ActiveRecord::AssociationTypeMismatch (Sentence(#70119358770360) expected, got {"text"=>"extremely disappointed with the level of service with Virgin Media.", "tones"=>[{"score"=>0.64031, "tone_name"=>"Sadness"}, {"score"=>0.618451, "tone_name"=>"Confident
"}]} which is an instance of ActiveSupport::HashWithIndifferentAccess(#70119356172580)):

我最终为我的create动作编写了代码,该动作可以完成工作,但感觉很笨拙:

    project = Project.create({text: params[:text], title: params[:title], 
    img: params[:img]})
    params[:sentences].each do |sent|
      sentence = project.sentences.create({text: sent["text"]})
      sent["tones"].each do |tone|
        sentence.tones.create({score: tone["score"], tone_name: tone["tone_name"]})
      end
    end

    params[:tones].each do |tone|
      project.tones.create({score: tone["score"], tone_name: tone["tone_name"]})
    end

是否有比我上面刚刚尝试的更好的方法,我试图从嵌套的具有多个关联级别的对象创建对象?

0 个答案:

没有答案