点击"提交"我试图让两个表同时更新。在一种形式。有一个"锻炼"桌子和练习"表;锻炼has_many练习。出于某种原因,点击"提交"在表格上,只有"锻炼"表得到更新,而不是"练习"表。下面是控制器,视图和模型。我使用的是Ruby 2.3,Rails 5.0和Windows PC。
锻炼控制器(workouts_controller.rb)
class WorkoutsController < ApplicationController
def new
@workout = Workout.new
@workout.exercises.build
end
def create
@workout = Workout.create(workout_params)
if @workout.save
redirect_to @workout
end
end
def show
@workout = Workout.find(params[:id])
@exercises = @workout.exercises
end
private
def workout_params
params.require(:workout).permit(:workout_length, :workout_description, :video_url, exercises_attributes: [:exercise_description])
end
end
新锻炼视图(锻炼\ new.html.erb)
<h1>Create New Workout</h1>
<%= form_for(@workout) do |f| %>
<%= f.number_field :workout_length, :placeholder => "Workout length (minutes)" %> <br>
<%= f.text_field :workout_description, :placeholder => "Workout description" %> <br>
<%= f.url_field :video_url, :placeholder => "Video URL" %> <br>
<%= fields_for :exercises do |builder| %>
<p>
<%= builder.label :exercise_description %>
<%= builder.text_field :exercise_description %>
</p>
<% end %>
<%= f.submit "SUBMIT WORKOUT" %>
<% end %>
锻炼模型(workout.rb)
class Workout < ActiveRecord::Base
has_many :exercises, :dependent => :destroy
accepts_nested_attributes_for :exercises
validates_associated :exercises
end
运动模型(exercise.rb)
class Exercise < ActiveRecord::Base
belongs_to :workout
end
锻炼迁移(_create_workouts.rb)
class CreateWorkouts < ActiveRecord::Migration[5.0]
def change
create_table :workouts do |t|
t.integer :workout_length
t.string :workout_description
t.string :video_url
t.timestamps
end
end
end
练习迁移(_create_exercises.rb)
class CreateExercises < ActiveRecord::Migration[5.0]
def change
create_table :exercises do |t|
t.string :exercise_description
t.references :workout, foreign_key: true
t.timestamps
end
end
end
我提交表格后,&#34;锻炼&#34;表按预期通过INSERT语句更新,但是&#34;练习&#34; table没有任何新行...没有为&#34; exercise&#34;执行INSERT语句。关于为什么&#34;练习&#34;表没有得到更新???
答案 0 :(得分:2)
如果您对嵌套属性执行fields_for
,则必须使用属于更高级别表单对象的fields_for
方法。
所以不要......
<%= fields_for :exercises do |builder| %>
...做
<%= f.fields_for :exercises do |builder| %>