Question

I'm trying to get categories and subcategories working. So far, I can create categories and add subcategories to them. When I submit the form, the subcategories_attributes send, but no Subcategory records are created. Please help, I'm pulling my hair out over here, and none of the tutorials seem to be helping.

category.rb

class Category < ActiveRecord::Base
   has_many :subcategories, :dependent => :destroy
   accepts_nested_attributes_for :subcategories, :reject_if => lambda {|a| 
   a[:content].blank?}
end

subcategory.rb

class Subcategory < ActiveRecord::Base
   belongs_to :category
end

categories_controller.rb

class CategoriesController < ApplicationController
   before_action :set_category, only: [:show, :edit, :update, :destroy]

def index
   @categories = Category.all
end

def show
end

def new
   @category = Category.new
   @category.subcategories.build
end

def edit
end

def create
   @category = Category.new(category_params)

   respond_to do |format|
     if @category.save
       format.html { redirect_to @category, notice: 'Category was successfully 
       created.' }
       format.json { render action: 'show', status: :created, location: @category }
     else
       format.html { render action: 'new' }
       format.json { render json: @category.errors, status: :unprocessable_entity }
     end
   end
end

def update
   respond_to do |format|
     if @category.update(category_params)
       format.html { redirect_to @category, notice: 'Category was successfully 
       updated.' }
       format.json { head :no_content }
     else
       format.html { render action: 'edit' }
       format.json { render json: @category.errors, status: :unprocessable_entity }
     end
   end
end

def destroy
   @category.destroy
   respond_to do |format|
     format.html { redirect_to categories_url }
     format.json { head :no_content }
   end
end

private
# Use callbacks to share common setup or constraints between actions.
  def set_category
    @category = Category.find(params[:id])
  end

# Never trust parameters from the scary internet, only allow the white list through.
  def category_params
    params.require(:category).permit(:name, subcategories_attributes: [:id, :name, 
    :_destroy])
  end
end

_form.html.erb

<%= nested_form_for(@category) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category 
      from being saved:</h2>   
      <ul>
      <% @category.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <%f.fields_for :subcategories do |builder|%>
    <p>
      <b>Subcategory</b>
      <%=builder.text_field :name%>
      <%=builder.link_to_remove "Remove"%>
    <p>
  <%end%>
    <p>
      <%=f.link_to_add "Add a Subcategory", :subcategories%>
    </p>    

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Params Hash (on submit):

  Parameters: {"utf8"=>"✓", 
  "authenticity_token"=>"19FxRnWF1F3BD4QZIkkce4arkOPt/BMkWFw6Z+vpV+8=", "category"=>
  {"name"=>"Test", "subcategories_attributes"=>{"1398706662184"=>{"name"=>"TS1", 
  "_destroy"=>"false"}, "1398706664804"=>{"name"=>"TS2", "_destroy"=>"false"}}}, 
  "commit"=>"Create Category"} 

Thanks in advance!

Was it helpful?

Solution

subcategories_attributes are sent correctly within your params hash BUT content attribute is missing in them.

"subcategories_attributes"=>{"1398706662184"=>{"name"=>"TS1", 
  "_destroy"=>"false"}, "1398706664804"=>{"name"=>"TS2", "_destroy"=>"false"}}

Notice there is no content key passed. So, all the subcategories records passed in subcategories_attributes are REJECTED due to the condition you specified in Category model:

 accepts_nested_attributes_for :subcategories, :reject_if => lambda {|a| 
   a[:content].blank?}

Notice :reject_if => lambda {|a| a[:content].blank?} part above, this will reject all the records for which content is missing.

UPDATE

when I go to my edit action, the fields don't show up, despite being added to the database as intended (and showing up as such in other forms).

Set a variable in edit and new actions as below:

def new
 @category = Category.new
 @subcategories = @category.subcategories.build ## Added
end

def edit
  @subcategories = @category.subcategories  ## Added
end

Update the fields_for in edit form as below:

<%= f.fields_for :subcategories, @subcategories do |builder|%>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top