我有一个让我很困惑的问题。
我有四个模型,一个锻炼模型,一个锻炼模型,一个exercise_exercise连接模型和一个workout_exercise_set模型。
我可以通过workout_exercises连接表为锻炼添加练习。现在我正在尝试将训练集添加到练习中,这就是workout_exercises_sets表的用途。
这是一个例子。
Workout
Exercise 1
Set 1
Set 2
Set 3
Exercise 2
Set 1
Set 2
Set 3
Exercise 3
etc.
在workouts/edit.html.erb
我有一个表单,我可以在其中查看锻炼中的所有练习,并使用form_for
和fields_for
编辑集合数量,但是当我尝试更新时锻炼或整个锻炼我得MassAssignmentSecurity::Error in WorkoutsController#update
说Can't mass-assign protected attributes: workout_exercise_sets
。我无法弄清楚如何克服这个问题。我知道我正在编辑锻炼,但我不是要写一个名为workout_exercise_sets
的字段,所以我真的很困惑。我非常感谢任何指导。所有相关代码如下。
workout/edit.html.erb:
<%= form_for(@workout) do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %><br />
<%= f.label :description %><br>
<%= f.text_area :description %></br>
<%= f.fields_for :workout_exercises do |s| %>
<%= s.object.exercise.name %></b>
<%= s.fields_for :workout_exercise_sets do |set| %>
<%= set.label :set_number %>:
<%= set.number_field :set_number %>
<%= set.label :reps %>:
<%= set.number_field :repetitions %>
<%= set.label :rest_time %>(seconds):
<%= set.number_field :rest_time %>
<%= set.submit %>
<% end %>
<%= s.hidden_field :_destroy %>
<%= link_to "Remove exercise?", '#', class: "remove_fields" %>
<% end %>
<%= f.submit %>
<% end %>
这是锻炼模型:
class Workout < ActiveRecord::Base
attr_accessible :name, :exercises_attributes, :workout_exercises_attributes, :exercise_order, :description
has_many :workout_exercises, dependent: :destroy, :order => "exercise_order DESC"
has_many :exercises, through: :workout_exercises
accepts_nested_attributes_for :exercises
accepts_nested_attributes_for :workout_exercises, allow_destroy: :true
end
以下是运动模型:
class Exercise < ActiveRecord::Base
attr_accessible :name, :description
has_many :workout_exercises
has_many :workouts, through: :workout_exercises
validates :name, uniqueness: :true, presence: :true
validates :description, uniqueness: :true, presence: :true
end
这是workout_exercise模型:
class WorkoutExercise < ActiveRecord::Base
attr_accessible :exercise_id, :workout_id
belongs_to :exercise
belongs_to :workout
has_many :workout_exercise_sets, dependent: :destroy
accepts_nested_attributes_for :workout_exercise_sets, allow_destroy: :true
end
最后,这是workout_exercise_sets模型:
class WorkoutExerciseSet < ActiveRecord::Base
attr_accessible :repetitions, :rest_time, :set_number, :workout_exercise_id
belongs_to :workout_exercise
end
为了更好地衡量,这是DB的图表:
答案 0 :(得分:1)
我认为在您的workout_excercise.rb
文件中,您应该将:workout_exercise_sets_attributes
添加到attr_accessible
列表中。
class WorkoutExercise < ActiveRecord::Base
attr_accessible :exercise_id, :workout_id, :workout_exercise_sets_attributes
belongs_to :exercise
belongs_to :workout
has_many :workout_exercise_sets, dependent: :destroy
accepts_nested_attributes_for :workout_exercise_sets, allow_destroy: :true
end