Rails has_one关联预期Model got String

时间:2016-04-12 10:58:50

标签: ruby-on-rails ruby simple-form cocoon-gem

在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_formcocoon来处理顶层模型(Workout)上的嵌套模型创建我在为sets和{{构建表单时遇到了麻烦1}} - 更简洁,当将stepsworkout_set相关联(并将参数列入白名单)时,我遇到以下错误:

  

视频(#70285207226600)预期,得到字符串(#70285080848240)

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

params

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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