chords/:id/show ページにフォームがあります (以下を参照)。:note_id をフォームに入力すると、:params の :chord_id とフォームの :note_id を使用して ChordNote が作成されます。これはうまくいきます。ただし、同じフォームを使用して ChordNote を削除しようとすると、次のようなエラーが表示されます。
ChordNotesController#destroy の NoMethodError、nil:nilClass の未定義メソッド '[]'
和音と音符を多対多の関係で結合する「ChordNote」のコントローラーです。
def create
@chord = Chord.find(params[:chordnote][:chord_id])
@note = Note.find(params[:chordnote][:note_id])
if @chord.hasnote?(@note)
# Add error message here, have it not redirect
redirect_to @chord
else
@chord.addnote!(@note)
redirect_to @chord
end
end
def destroy
@chord = Chord.find(params[:chordnote][:chord_id])
@note = Note.find(params[:chordnote][:note_id])
Chordnote.find_by(note_id: @note.id, chord_id: @chord.id).destroy
redirect_to chord_path(@chord)
end
これはフォームです (chords/:id/show に表示されます):
<%= form_for(@chord.chordnotes.build(chord_id: @chord.id)) do |f| %>
<div><%= f.hidden_field :chord_id, value: @chord.id %></div>
<div class="field">
<%= f.text_field :note_id, placeholder: "Enter the note's id" %>
</div>
<%= f.submit "Add Note", class: "btn btn-large" %>
<%= link_to "Remove Note", Chordnote.find_by(note_id: 1), method: :delete, title: "test title", class: "btn btn-large" %>
<% end %>
なぜdestroyが機能しないのかについて何か考えはありますか? ありがとう!
nil:NilClass の未定義メソッド `[]'
def destroy
####The error is on the following line####
@chord = Chord.find(params[:chordnote][:chord_id])
@note = Note.find(params[:chordnote][:note_id])
Chordnote.find_by(note_id: @note.id, chord_id: @chord.id).destroy
redirect_to chord_path(@chord)
Rails.root: /Users/mydocs/myprojects/rails_projects/what_key_v002
Application Trace | Framework Trace | Full Trace
app/controllers/chordnotes_controller.rb:23:in `destroy'
Request
投稿されたパラメーター:
{"_method"=>"delete",
"id"=>"10"}