Formtastic Nesting帮助

时间:2011-06-30 23:06:22

标签: ruby-on-rails-3 formtastic

我正在尝试熟悉以下情况。

routine.rb

class Routine < ActiveRecord::Base
  has_many :exercise_routines
  has_many :exercises, :through => :exercise_routines
  accepts_nested_attributes_for :exercise_routines
end

exercise_routine.rb

class ExerciseRoutine < ActiveRecord::Base
  belongs_to :exercise
  belongs_to :routine
  has_many :attempts
  accepts_nested_attributes_for :attempts
end

show.html#/ routines / show.html.haml

%h2 Exercises:

%ol
  - for exercise_routine in @routine.exercise_routines
    %li= exercise_routine.exercise.name
    %ul
      %li
        = exercise_routine.sets
        Sets
      %li
        = exercise_routine.reps
        Reps
      %li
        Attempt: 
        - for attempt in exercise_routine.attempts
          = attempt.reps
        = semantic_form_for @routine do |routine|
          = routine.semantic_fields_for exercise_routine do |exercise_routine|
            = exercise_routine.semantic_fields_for :attempts do |attempt|
              = attempt.input :reps, :required => false
          = routine.buttons`

我遇到的麻烦是两件事: 1)如果我通过控制台手动添加它,这是成功呈现每个例程的尝试但是如果我尝试更新它,我会得到:“unknown attribute:exercise_routine”并且我意识到因为params:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"51fZRe1wKRQoVUz+lGlldd4DmMODGHN203Htc4DEi0Y=",
 "routine"=>{"exercise_routine"=>{"attempts_attributes"=>{"0"=>{"reps"=>"5",
 "id"=>"1"},
 "1"=>{"reps"=>"1555",
 "id"=>"2"},
 "2"=>{"reps"=>""}}}},
 "commit"=>"Update Routine",
"id"=>"3"}`

看起来不对。它应该引用带有id的exercise_routines。

2)希望能够同时添加尝试。

@routine.exercise_routines.each do |er|
  1.times {er.attempts.build}
end

正确渲染它但当然我遇到了同样的params问题。我要么做一些愚蠢的错误,要么这比我想做的这种多重集合嵌套更难?

1 个答案:

答案 0 :(得分:0)

您没有正确使用fields_for。第一个参数必须用于嵌套字段的关联。然后,第二个可以是用于关联值的/单个模型的集合。

= routine.semantic_fields_for :exercise_routines, exercise_routine do |f|

另外,我建议不要将第一个本地exercise_routine隐藏在块内的表单构建器本地。我会使用@routine.exercise_routines.each do |exercise_routine|表单而不是for循环。