V
V
V2015-05-29 18:44:58
MongoDB
V, 2015-05-29 18:44:58

Why doesn't nested attributes work in Mongoid?

I want to do a very common thing: create a multi-model form. For some reason, the collection field does not appear on the item creation page.

class Item
  include MongoMapper::AcceptsNestedAttributes
  include Mongoid::Document
  include Mongoid::Timestamps
  has_many :statuses, dependent: :delete, autosave: true
  has_one :collection
  field :name, type: String
  field :description, type: String
  field :cost, type: BigDecimal

  accepts_nested_attributes_for :collection, autosave: true
end

class Collection
  include Mongoid::Document
  belongs_to :item
  field :name, type: String
end

def new
    @item = Item.new
  end

  def create
    @item = Item.new(item_params)
    respond_to do |format|
      if @item.save
        format.html { redirect_to @item, notice: 'Item was successfully created.' }
        format.json { render :show, status: :created, location: @item }
      else
        format.html { render :new }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

= form_for @item do |f|
  .field
    = f.label :name
    br
    = f.text_field :name, class: "form-control"
  .field
    = f.label :description
    br
    = f.text_area :description, class: "form-control" 
  .field
    = f.label :cost
    br
    = f.number_field :cost
  .field
    = f.fields_for :collection do |builder|
      = builder.label :collection, "Collection"
      = builder.text_field :name, collection: ['Car', 'Truck']
  .actions = f.submit

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jeiwan, 2015-05-30
@ermolushka

If Item does not have a Collection, then there will be no field, so the second parameter in fields_for must be passed the initialized model:

= f.fields_for :collection, @item.collection.new do |builder|

V
V, 2015-05-30
@ermolushka

I fixed it, and the field appeared (also, I had to change the name from Collection to Category: apparently mongodb does not like Collection). But now for some reason it does not want to save this collection. I understand that the problem is somewhere in the attributes, here's how it is now:

def item_params
    params.require(:item).permit(:name, :description, :cost,
                                     category_attributes: [:id, :name])
end

def create
    @item = Item.new(item_params)
    @category = @item.create_category(params[:category])

def new
   @item = Item.new
   @category = @item.build_category
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question