2017-04-22 23 views
0

我想更新嵌套的属性但失败,例如有一篇文章,并且一本书有很多评论。当我发现我写的评论有一些错误,所以我想修改它。 这是我的代码。如何更新表格中的嵌套属性

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 %> 

什么我想更新注释而不改变codesnippets。我应该怎么做来改变我的代码。

回答

0

所以....还有很多事情在这里,所以我会通过建议在docs

首先仔细一看开始,让我们看看你的形式: CodeSnippet的has_many:注释

所以你的fields_for语句应该用于:注释,而不是:注释。语句的字段也不应该采用方法选项键。

接下来您的code_snippets_controller: 如文档所示,从嵌套属性表单发回的参数将在关键字annotations_attributes之下,并且将包含数组散列。

你需要让这个属性,你要传递到注释模型具有很强的参数任何属性:

params.require(:code_snippet).permit(annotations_params: [:some, : permitted, :params])

我相信这是所有你需要得到你的榜样工作。但是,如果遇到更多麻烦,我建议花几个binding.pry陈述来反省代码的实际行为。

+0

它不起作用,如果我改变了field_for的注释,它会显示codesnippet的所有注释,我只是想修改其中的一个。我有做这个添加在code_snippet_params annotations_params: ''' 私人 高清code_snippet_params params.require(:CODE_SNIPPET).permit(:片断,annotations_params::用户:行:正文]) 结束 ''' – AlexKIe