Rails has_one relationship和simple_form

时间:2016-04-11 16:17:20

标签: ruby-on-rails simple-form polymorphic-associations

使用simple_form为WorkoutSet模型构建嵌套表单,其中包含以下字段:

  • intro_video
  • get_ready
  • outro_video
  • WorkoutStep(另一个嵌套模型)

我希望能够从选择

中选择intro_video

由于WorkoutSet位于Workout内,表单如下所示: WorkoutSet.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

_form.html.haml

  %h2 Sets
  .sets.some{ :style => "margin-left: 25px" }
    = f.simple_fields_for :workout_sets do |set|
      = render 'workout_set_fields', f: set
    .links
      .button-row
        = link_to_add_association 'add set', f, :workout_sets

_workout_set_fields.html.haml

.nested-fields
  %h2 New set - #{link_to_remove_association 'Delete', f}
  = f.label :title
  = f.text_field :title

  = f.input :intro_video, :collection => Video.all, :label_method => :title, :value_method => :id, :include_blank => false

  %br
  %br
  #sets.some{ :style => "margin-left: 25px" }
    = f.simple_fields_for :workout_steps do |step|
      = render 'workout_step_fields', f: step
    .links
      .button-row
        = link_to_add_association 'add step', f, :workout_steps

渲染选择并且值看起来很好,直到我将模型保存为白名单以下参数:

params.require(:workout).permit(:title, :pro, :image, warmup_attributes: [:id, :_destroy, {main_video_ids: []}], workout_sets_attributes: [:id, :_destroy, :title, :intro_video, workout_steps_attributes: [:id, :_destroy, {main_video_ids: []}] ])

此外,我注意到在f.input :intro_video行中,正在发送的参数是intro_video,而不是intro_video_attributes

提前致谢。

0 个答案:

没有答案