ネストされた属性を更新したいが失敗した。例えば記事があり、書籍には多くのコメントがある。私が書いたコメントにいくつかの間違いがあるので、私はそれを修正したいと思う。 ここに私のコードです。フォーム内にネストされた属性を更新する方法
code_snippet.rb
において:
class CodeSnippet < ApplicationRecord
has_many :annotations, dependent: :destroy
accepts_nested_attributes_for :annotations ,update_only: true ,reject_if: :all_blank, allow_destroy: true
end
annotation.rb
において:
class Annotation < ApplicationRecord
belongs_to :code_snippet
end
code_snippet_controller.rb
において:
def edit
@code_snippet = CodeSnippet.find(params[:id])
end
def update
@code_snippet = CodeSnippet.find(params[:id])
if @code_snippet.update(code_snippet_params)
redirect_to @code_snippet
else
render 'edit'
end
end
private
def code_snippet_params
params.require(:code_snippet).permit(:snippet)
end
annotation.rb
において:
def edit
@code_snippet = CodeSnippet.find(params[:code_snippet_id])
@annotation = @code_snippet.annotations.find(params[:id])
end
def update
@code_snippet = CodeSnippet.find(params[:id])
@annotation = @code_snippet.annotations.find(params[:id])
if @annotation.update(annotation_params)
redirect_to @code_snippet
else
render 'edit'
end
end
での見解/ code_snippets/show.html.rb「
<div>
<h2>Annotations</h2>
<%= render @code_snippet.annotations %>
</div>
での見解/注釈/ _annotation.html.erb '/編集見解/注釈で
<p>
<strong>User:</strong>
<%= annotation.user %>
</p>
<p>
<strong>Line:</strong>
<%= annotation.line %>
</p>
<p>
<strong>Body:</strong>
<%= annotation.body %>
</p>
<p>
<%= link_to "Edit", edit_code_snippet_annotation_path(annotation.code_snippet,annotation) ,controller: 'annotation'%>
</p>
。 html.erb ':
<%= form_for(@code_snippet) do |f| %>
<%= f.fields_for :annotation,method: :patch do |builder| %>
<p>
<%= builder.label :user %><br>
<%= builder.text_field :user %>
</p>
<p>
<%= builder.label :line %><br>
<%= builder.text_field :line %>
</p>
<p>
<%= builder.label :body %><br>
<%= builder.text_area :body %>
</p>
<p>
<%= builder.submit %>
</p>
<% end %>
<% end %>
私は、コードニップを変更することなく注釈を更新したいと思います。コードを変更するにはどうすればよいですか。
注釈のfield_forを変更すると、コードニットのすべての注釈が表示されますが、そのうちの1つを変更したいだけです。そして、私はこれを行うことにより、code_snippet_paramsでannotations_paramsを追加する必要があり:(:、スニペットannotations_params:[:ユーザー、:ライン、:ボディ]):(CODE_SNIPPET).permit DEF params.requireをcode_snippet_params '' ' プライベート エンド '' '' – AlexKIe