Ruby 在 Rails - 为什么我面临可能无法匹配的约束[:exercise_id]

Ruby on Rails - why i am facing possible unmatched constraints[:exercise_id]

def edit    
  @exercise = Exercise.find(params[:exercise_id])      
  @play = @exercise.plays.find(params[:id])    
end

def update    
  @exercise = Exercise.find(params[:exercise_id])
  @play = @exercise.plays.find(params[:id])    
  if @exercise.plays.update_attributes(play_params)       
    redirect_to @exercise_path      
  else    
    render action: :edit    
  end
end

正在渲染以显示所有创建的剧本的部分视图有

<p><%= play.name %></p>
<p><%= play.sets %></p>
<p><%= play.reps %></p>
<%= link_to "edit", edit_exercise_play_path( @exercise, play) %>

即plays_controller :edit, :update 方法,实际上我有两个类,一个是ExerciseController,另一个是PlaysControllerExerciseController has_many 播放,我正在渲染两个部分,一个用于创建播放,另一个用于显示在创建后渲染播放的部分的同一页面上播放,但现在我想添加 [=34 的编辑功能=],

<%= link_to "Edit", edit_exercise_play_path(@play) %>

在此之后我面临着无与伦比的约束error.Thanks

resources :exercises do
resources :plays
end

Show.html.erb 来自 ExercisesController

<h2>Your Workout Details </h2>
<p><%= @exercise.workout  %></p>
<p><%= @exercise.mode %></p>
<p><%= @exercise.date.strftime("on %A at %H:%M Dated as %d %B") %></p>
<p><%= @exercise.length %></p><br />
<h3> Games you Played </h3>
<%= render @exercise.plays %>
<h3>Add new Game </h3>
<%= render 'plays/form' %>
<%= link_to "Edit", edit_exercise_path %> |  |
<%= link_to "Destroy", exercise_path(@exercise), :confirm => "Are you 
sure?", :method => :delete %> | |
<%= link_to "Back", root_path %>

" Logs " Started GET "/exercises/5" for 127.0.0.1 at 2018-09-25 18:12:21 +0500 Processing by ExercisesController#show as HTML Parameters: {"id"=>"5"} Exercise Load (0.0ms) SELECT "exercises".* FROM "exercises" WHERE "exercises"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]] Rendering exercises/show.html.erb Play Load (0.0ms) SELECT "plays".* FROM "plays" WHERE "plays"."exercise_id" = ? [["exercise_id", 5]] Rendered collection of plays/_play.html.erb [6 times] (14.0ms) Rendered exercises/show.html.erb (39.7ms) Completed 500 Internal Server Error in 136ms (ActiveRecord: 0.0ms)

根据您的路线,路径助手 edit_exercise_play_path 还需要 :exercise_id 键的值。但是你没有通过任何。将 link_to 更改为以下应该可以解决您的问题

<%= link_to "Edit", edit_exercise_play_path(@exercise, @play) %>

更新:

根据我们在聊天中的讨论,link_to 编辑应该如下所示

<%= link_to "Edit", edit_exercise_play_path(@exercise, play) %>

当您使用 <%= render @exercise.plays %> 渲染局部时,它会创建一个 play 变量。

undefined method `model_name' for nil:NilClass

为此,您应该将 <%= render 'form' %> 更改为 <%= render 'form' , exercise: @exercise, play: @play %>,并在 _form.html.erb 中将表格的第一行更改为 <%= simple_form_for ([exercise, play]) do |f| %>

undefined method `update_attributes' for Play::ActiveRecord_Associations_CollectionProxy:0x0000000f69c710

此错误的原因在于您的更新方法@exercise.plays.update_attributes(play_params)。这意味着您在收集时调用 update_attributes。你应该改变

if @exercise.plays.update_attributes(play_params)

if @play.update_attributes(play_params)