2016-10-27 64 views
1

真的很難倒在這裏。我試圖讓我的表單更新edit表單中的類別。問題是,除了類別以外,我的表單中的所有內容都會更新。它最終會插入選擇的新類別,如通過create方法而不是update方法,因此在提交後再次顯示編輯表單時,它會使類別字段翻倍。 1,然後是2,然後是4,然後是8,等等。請幫助任何人。欣賞它。在Rails中更新嵌套fields_for和collection_select

視圖/ blog_posts/edit.html.erb

<div class="col-md-6 col-md-offset-3 blog-submit"> 
      <%= form_for @blog_post do |b| %> 


      <%= b.label :title %> 
      <%= b.text_field :title %><br> 

       <%= b.fields_for :categorizations do |cat| %> 
       <%= cat.label :category_name, "Category 1" %> 
       <%= cat.collection_select(:category_id, Category.all, :id, :category_name, {blank: "Select Category"}) %> 
       <%= link_to "Add Categories", new_category_path %> 
        <br> 
       <% end %> 

       <%= b.submit "Submit", class: "btn btn-primary" %> 
      <% end %> 
     </div> 

Blog_post控制器:

class BlogPostsController < ApplicationController 
    protect_from_forgery 
    before_action :authenticate_admin!, only: [:new, :edit] 

    def index 
     @blog_posts = BlogPost.order(id: :desc) 
    end 

    def new 
     @blog_post = BlogPost.new 
     @blog_post.categorizations.build.build_category 
     @blog_post.categories.build 
    end 

    def edit 
     @blog_post = BlogPost.find(params[:id]) 
    end 

    def create 
     @blog_post = BlogPost.new(blog_post_params) 
     respond_to do |format| 
      if @blog_post.save 
      format.html { redirect_to @blog_post, notice: 'Your blog was submitted successfully' } 
      format.json { render :show, status: :created, location: @blog_post } 
      else 
      format.html { render :new } 
      format.json { render json: @blog_post.errors, status: :unprocessable_entity } 
      end 
     end 
     puts @blog_post.errors.inspect 
    end 

    def update 
     @blog_post = BlogPost.find(params[:id]) 
     if @blog_post.update_attributes(blog_post_params) 
      render 'show' 
     else 
      render 'edit' 
     end 
    end 

    def show 
     @blog_post = BlogPost.find(params[:id]) 

    end 



private 

    def blog_post_params 
    params.require(:blog_post).permit(:title, :content, :posted_by, :comments, :blog_pic, {categorizations_attributes: [:category_id, :category_name]}) 
    end 

end 

機型:

class BlogPost < ApplicationRecord 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 
    accepts_nested_attributes_for :categorizations 
    has_many :comments 
    mount_uploader :blog_pic, BlogPicUploader 
end 

class Categorization < ApplicationRecord 
    belongs_to :blog_post 
    belongs_to :category 
end 

class Category < ApplicationRecord 
    has_many :categorizations 
    has_many :blog_posts, :through => :categorizations 
end 

回答

2

blog_post_params添加id如下所示。這將爲你工作。

def blog_post_params 
    params.require(:blog_post).permit(:title, :content, :posted_by, :comments, :blog_pic, {categorizations_attributes: [:id,:category_id, :category_name]}) 
    end