Rails has_one 关联预期模型得到字符串

Rails has_one association expected Model got String

3 个模型之间有以下关联:

workout.rb

class Workout < ActiveRecord::Base
  has_and_belongs_to_many :workout_sets, :join_table => :workout_sessions
  belongs_to :warmup, :class_name => :WorkoutStep, :foreign_key => "workout_step_id"
  accepts_nested_attributes_for :workout_sets, allow_destroy: true
  accepts_nested_attributes_for :warmup, allow_destroy: true
end

workout_set.rb

class WorkoutSet < ActiveRecord::Base
  has_and_belongs_to_many :workout_steps, :join_table => :sets_steps, dependent: :destroy
  has_and_belongs_to_many :workouts, :join_table => :workout_sessions
  accepts_nested_attributes_for :workout_steps, allow_destroy: true

  has_one :intro_video_usage, class_name: 'VideoUsage::Intro', as: :parent, dependent: :destroy
  has_one :intro_video, through: :intro_video_usage, source: :video

  accepts_nested_attributes_for :intro_video

  has_one :get_ready_video_usage, class_name: 'VideoUsage::GetReady', as: :parent, dependent: :destroy
  has_one :get_ready_video, through: :get_ready_video_usage, source: :video

  has_one :congrats_video_usage, class_name: 'VideoUsage::Congratulations', as: :parent, dependent: :destroy
  has_one :congrats_video, through: :congrats_video_usage, source: :video
end

workout_step.rb

class WorkoutStep < ActiveRecord::Base
  has_and_belongs_to_many :workout_sets, :join_table => :sets_steps
  has_many :main_video_usage, class_name: 'VideoUsage::Main', as: :parent
  has_many :main_videos, through: :main_video_usage, source: :video
  accepts_nested_attributes_for :main_videos
end

并使用 simple_form and cocoon 处理顶层模型 (Workout) 上的嵌套模型创建 我在为 setssteps 构建表单时遇到问题 -更简洁,当将 workout_setintro_video 相关联(并将参数列入白名单)时,我遇到以下错误:

Video(#70285207226600) expected, got String(#70285080848240)

发送后的params对象如下所示:

"workout"=>{"title"=>"",
 "workout_sets_attributes"=>{"0"=>{"_destroy"=>"false",
 "intro_video"=>"70",
 "title"=>""}}},
 "image"=>"",
 "sound_logo"=>"",
 "intro_video"=>"",
 "commit"=>"Create workout"}

提前致谢。

您的参数正在将字符串 ("70") 传递给 intro_video=,但是像这样的关联访问器希望您传递关联 class 的实际实例(在本例中为视频)。

您应该改为分配给 intro_video_id。访问器将为您将字符串转换为整数。