0

幾個小時試圖研究一個解決方案,發現一些非常類似的問題like this onethis one,雖然所有建議的修補程序不' t解決我的問題:嵌套窗體內嵌套窗體 - 繭寶石:3級孩子不保存 - Rails 5

嘗試使用Cocoon Gem在嵌套窗體內部構建一個嵌套窗體,儘管第三級子窗體不保存到數據庫。

的車型很簡單的結構,只有 「的has_many/belongs_to的」 關係:

文本有很多的報價。報價有很多評論。

在實現中的動態UI交互工作,添加和刪除字段的工作,但不幸的是,只有文本和引號被保存,而不是註釋。沒有顯示錯誤。

這裏是形式:

_text_form.html.erb

<%= form_for(@text, html: { multipart: true }) do |f| %> 
    <%= render 'shared/error_messages', object: f.object %> 
    <div class="field"> 
    <%= f.text_field :title, placeholder: "Enter Title" %>  
    </div> 
    <div> 
     <h3>Quotes:</h3> 
     <div id="quotes"> 
     <%= f.fields_for :quotes do |quote| %> 
      <%= render 'quote_fields', f: quote %> 
     <% end %> 

     <div class="links"> 
      <%= link_to_add_association 'add quote', f, :quotes, class: "btn btn-default" %> 
     </div> 
     </div> 
    </div> 

    <%= f.submit %> 
<% end %> 

_quote_fields.html.erb

<div class="nested-fields"> 
    <%= f.text_area :content, placeholder: "Compose new quote..." %> 
    <span class="picture"> 
    <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %> 
    </span> 

    <div> 
     <h3>Comments:</h3> 
     <div id="comments"> 
     <%= f.fields_for :comments do |comment| %> 
      <%= render 'comment_fields', f: comment %> 
     <% end %> 
     <div class="links"> 
      <%= link_to_add_association 'add comment', f, :comments, class: "btn btn-default" %> 
     </div> 
     </div> 
    </div> 
    <div class="links"> 
    <%= link_to_remove_association "remove quote", f, class: "btn btn-default" %> 
    </div> 
</div> 

<script type="text/javascript"> 
    $('#quote_picture').bind('change', function() { 
    var size_in_megabytes = this.files[0].size/1024/1024; 
    if (size_in_megabytes > 2) { 
     alert('Maximum file size is 2MB. Please choose a smaller file.'); 
    } 
    }); 
</script> 

_comment_fields.html.erb

<div class="nested-fields"> 
    <%= f.text_area :bodycomment, placeholder: "Write a comment..." %> 
    <%= link_to_remove_association "remove comment", f, class: "btn btn-default" %> 
</div> 

下面是型號:

text.rb

class Text < ApplicationRecord 
    belongs_to :user, inverse_of: :texts 
    has_many :quotes, dependent: :destroy, inverse_of: :text 
    has_many :comments, :through => :quotes 
    accepts_nested_attributes_for :quotes, reject_if: :all_blank, allow_destroy: true 
    accepts_nested_attributes_for :comments, reject_if: :all_blank, allow_destroy: true 
    default_scope -> { order(created_at: :desc) } 
    mount_uploader :coverimage, CoverimageUploader 

    validates :user_id, presence: true 
    validates :title, presence: true 
    validate :coverimage_size 

    private 

     # Validates the size of an uploaded picture. 
     def coverimage_size 
     if coverimage.size > 5.megabytes 
      errors.add(:coverimage, "should be less than 5MB") 
     end 
     end 

end 

quote.rb

class Quote < ApplicationRecord 
    belongs_to :text, inverse_of: :quotes 
    has_many :comments, dependent: :destroy, inverse_of: :quote 
    accepts_nested_attributes_for :comments, reject_if: :all_blank, allow_destroy: true 

    mount_uploader :picture, PictureUploader 
    validates :content, presence: true, length: { maximum: 350 } 
    validate :picture_size 

private 

    #Validates size of image upload 
    def picture_size 
    if picture.size > 2.megabytes 
     errors.add(:picture, "should be less than 2MB") 
    end 
    end 

end 

comment.rb

class Comment < ApplicationRecord 
    belongs_to :quote, inverse_of: :comments 
    validates :quote_id, presence: true 
    validates :bodycomment, presence: true 

end 

這裏控制器:

quotes_controller.rb

class QuotesController < ApplicationController 
before_action :logged_in_user, only: [:create, :destroy] 
before_action :correct_user, only: :destroy 


    def show 
    end 



    def create 
    @quote = current_user.quotes.build(quote_params) 
    if @quote.save 
    flash[:success] = "Quote created!" 
    redirect_to root_url 
    else 
    @feed_items = [] 
    render 'static_pages/home' 
    end 
    end 

    def destroy 
    @quote.destroy 
    flash[:success] = "Quote deleted" 
    redirect_to request.referrer || root_url 
    end 


    private 

    def quote_params 
     params.require(:quote).permit(:content, :picture, comments_attributes: [:id, :bodycomment 
     , :_destroy]) 
    end 

    def correct_user 
     @quote = current_user.quotes.find_by(id: params[:id]) 
     redirect_to root_url if @quote.nil? 

    end 

end 

comments_controller.rb

class CommentsController < ApplicationController 
before_action :logged_in_user, only: [:create, :edit, :update, :destroy] 
before_action :correct_user, only: :destroy 


    def show 
    end 

    def create 
     @comment = current_user.comments.build(comment_params) 
     if @comment.save 
      flash[:success] = "Comment created!" 
      redirect_to root_url 
     else 
      @feed_items = [] 
      render 'static_pages/home' 
     end 
     end 

    def destroy 
     @comment.destroy 
     flash[:success] = "Comment deleted" 
     redirect_to request.referrer || root_url 
    end 

    private 

    def comment_params 
      params.require(:comment).permit(:bodycomment) 
    end 

    def correct_user 
     @comment = current_user.comments.find_by(id: params[:id]) 
     redirect_to root_url if @comment.nil? 

    end 

end 

想知道是否有一些JavaScript的問題...

非常感謝您的關注。非常感謝,並感謝您的幫助。

編輯

這裏是texts_controller。RB

class TextsController < ApplicationController 
    before_action :logged_in_user, only: [:create, :edit, :update, :destroy] 
    before_action :correct_user, only: :destroy 
    before_action :find_text, only: [:show, :edit, :update, :destroy] 


    def show 
    end 

    def new 
    @text = current_user.texts.build 
    end 

    def create 
    @text = current_user.texts.build(text_params) 
    if @text.save 
    flash[:success] = "Text created!" 
    render 'show' 
    else 
    render 'static_pages/home' 
    end 
    end 


    def edit 
    end 

    def update 
    if @text.update(text_params) 
     redirect_to root_url 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    @text.destroy 
    flash[:success] = "Text deleted" 
    redirect_to request.referrer || root_url 
    end 

    private 

    def text_params 
    params.require(:text).permit(:url, :title, :coverimage, 
            :publication, :author, :summary, quotes_attributes: [:id, :content, :picture, :_destroy], comments_attributes: [:id, :bodycomment, :_destroy]) 
    end 

    def find_text 
     @text = Text.find(params[:id]) 
     end 

    def correct_user 
     @user = User.find(params[:id]) 
     redirect_to(root_url) unless current_user?(@user) 
    end 

end 

這裏有一些日誌的相關信息,我保存的表單字段後得到:

--- !ruby/object:ActionController::Parameters 
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
    utf8: "✓" 
    authenticity_token: NQLh7TwlhfbV4ez91HGMyYZK6YYYiLXhHG/cAhrAsRylIAuFFhjnKX0vEO8ZIVbsxGES3byBgUMz21aSOlGiqw== 
    text: !ruby/object:ActionController::Parameters 
    parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
     title: Title of the Book 
     quotes_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
     '1490626822148': !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
      content: This is a quote from the book. 
      _destroy: 'false' 
      comments_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
      '1490626833771': !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
       bodycomment: Here is a comment on the quote of the book. 
       _destroy: 'false' 
    permitted: false 
    commit: Create Text 
    controller: texts 
    action: create 
permitted: false 

這裏的日誌文件形成終端:

Started POST "/texts" for ::1 at 2017-03-27 17:00:51 +0200 
Processing by TextsController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"NQLh7TwlhfbV4ez91HGMyYZK6YYYiLXhHG/cAhrAsRylIAuFFhjnKX0vEO8ZIVbsxGES3byBgUMz21aSOlGiqw==", "text"=>{"title"=>"Title of the Book", "publication"=>"", "author"=>"", "url"=>"", "summary"=>"", "quotes_attributes"=>{"1490626822148"=>{"content"=>"This is a quote from the book.", "_destroy"=>"false", "comments_attributes"=>{"1490626833771"=>{"bodycomment"=>"Here is a comment on the quote of the book.", "_destroy"=>"false"}}}}}, "commit"=>"Create Text"} 
    User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] 
Unpermitted parameter: comments_attributes 
    (0.1ms) begin transaction 
    SQL (0.7ms) INSERT INTO "texts" ("user_id", "url", "title", "publication", "author", "summary", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["user_id", 1], ["url", ""], ["title", "Title of the Book"], ["created_at", 2017-03-27 15:00:51 UTC], ["updated_at", 2017-03-27 15:00:51 UTC]] 
    SQL (0.4ms) INSERT INTO "quotes" ("content", "created_at", "updated_at", "text_id") VALUES (?, ?, ?, ?) [["content", "This is a quote from the book."], ["created_at", 2017-03-27 15:00:51 UTC], ["updated_at", 2017-03-27 15:00:51 UTC], ["text_id", 366]] 
    (1.3ms) commit transaction 
    Rendering texts/show.html.erb within layouts/application 
    Quote Load (0.2ms) SELECT "quotes".* FROM "quotes" WHERE "quotes"."text_id" = ? [["text_id", 366]] 
    Rendered texts/show.html.erb within layouts/application (5.8ms) 
    Rendered layouts/_shim.html.erb (0.5ms) 
    Rendered layouts/_header.html.erb (1.4ms) 
    Rendered layouts/_footer.html.erb (1.8ms) 
Completed 200 OK in 127ms (Views: 100.1ms | ActiveRecord: 3.1ms) 
+1

你能告訴什麼是發佈到控制器? (你可以在日誌文件中找到它)並且你能夠顯示來自'TextsController'的強大參數定義(註釋和引用控制器與嵌套表單無關 - 整個表單發佈到textscontroler) – nathanvda

+0

... didn看到@nathanvda(寶石的製造者)在我發佈之前一直在這裏!哎呀! – Mirv

+0

@nathanvda真的很感激你正在研究這個!非常感謝。我添加了texts_controller.rb以及上面的一些日誌文件。 – YvonC

回答

2
  1. 模型.. text.rb ...我不得不把accepts_nested_attributes_for :comments ...除了已經發布的
  2. TextController ...您的嵌套允許PARAMS需要在這裏發生,.permit(:content, :picture, quotes_attributes: [:id, :content, :picture, :_destroy, comments_attributes: [:id, :bodycomment, :_destroy]])

我可能有變量名斷位(尤其是你沒有列出的TextController),但基本上,它看起來像你的正試圖通過其他控制器繼承嵌套 - 當唯一被調用的控制器是TextController時。

可以肯定的是,在第二個控制檯中放置一個tail -f log/<logname>,或者在執行保存/更新以查看許可問題時查看終端控制檯。

讓我知道是否仍然存在問題!根據新的控制器

...更新

控制器需要調整(你有一個放錯地方的「]」現在)。

params.require(:text).permit(:url, :title, :coverimage, 
            :publication, :author, :summary, quotes_attributes: [:id, :content, :picture, :_destroy, comments_attributes: [:id, :bodycomment, :_destroy]]) 

,直到你解決這個模型也將無法工作......

accepts_nested_attributes_for :comments 
+0

感謝您的幫助,並遺憾地忘記添加TextController ...以爲我會發布它。它現在在那裏。我嘗試在text.rb中添加「accep_nested_attributes_for」以用於評論...但是沒有成功。看到上面的日誌。 – YvonC

+2

好吧,所以問題看起來像2個部分 - 你需要添加accept_for返回&當你看看你的控制器允許的值爲TextController ...你沒有在'quotes'裏面的'comments',他們在那裏屬於......仔細閱讀我的答案,在#2的最後有兩個右括號(一個用於引號和一個用於註釋)彼此相鄰。 – Mirv

+0

Imho的'accepted_nested_attributes'已經可以,但是確實強的參數必須嵌套,如發送給控制器(並記錄在日誌文件中)所指示的那樣。 – nathanvda