V
V
V2016-08-16 15:38:43
MongoDB
V, 2016-08-16 15:38:43

How to work with array of dictionaries in mongoid?

In the database (users collection), records are stored in the following form:

"_id" : ObjectId("some id"),
  "admin" : "Name",
  "items" : [
    {
      "name" : "some name,
      "img" : "some url",
      "price" : 3000,
      "cat" : "category name",
      "active" : "1",
      "id" : 1,
      "desc" : "description"
    },

#_form.html.erb
<%= form_for(@bot) do |f| %>
  <div class="container">
    <div class="form-group">
      <%= f.label "Условия доставки" %><br>
      <%= f.text_area :delivery_info, class: "form-control"  %>
    </div>
    <div class="form-group">
      <%= f.label "Email" %><br>
      <%= f.text_field :email, class: "form-control"  %>
    </div>
    <div class="form-group">
      <%= f.label "Контактная информация" %><br>
      <%= f.text_area :contacts_info, class: "form-control"  %>
    </div>
    
    <div class="field">
      <%= @bot.items.each do |item| %>
        <%= f.fields_for item do |i| %>
      <div class="field">
        <%= i.label :name %><br />
        <%= i.text_field :name %>
      </div
        <% end %>
      <% end %>
    </div>
    <div class="actions">
      <%= f.submit "Сохранить", class: 'btn btn-success'%>
    </div>
  </div>
<% end %>

#item.rb
class Item
  include Mongoid::Document
  embedded_in :bot
  field :name, type: String
  field :price, type: Integer
  field :cat, type: String
  field :desc, type: String
  field :img, type: String
end

#bot.rb
require 'digest/md5'
class Bot
  include Mongoid::Document
  store_in collection: 'bots'
  embeds_many :items
  field :admin, type: String
  field :delivery_info, type: String
  field :email, type: String
  field :contacts_info, type: String
  field :link, type: String
  field :token, type: String
end

There are no problems with displaying a list of items for a specific user, but it is not clear how to edit item.
UPD: when I try to update the name value of an item, I get the message
Processing by BotsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"token here==", "bot"=>{" delivery_info"=>"Pickup", "email"=>"email here", "contacts_info"=>"telegram", "item"=>{"name"=>"Coat"}}, "commit"=>" Save", "id"=>"5790edbe3993951addde4b23"}
Unpermitted parameter: item
That is, it tries to change the item attribute, while the Bot model object has only the items attribute. It's not clear how to fix it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
V, 2016-08-17
@ermolushka

Decided by adding additional parameters to the controller.

V
Vlad_Fedorenko, 2016-08-16
@Vlad_Fedorenko

https://docs.mongodb.com/manual/reference/operator...
https://docs.mongodb.com/manual/reference/operator...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question