I have the following model:
class Entry
include Mongoid::Document
field :title, type: String
field :description, type: String
field :made, type: Date
embeds_many :images
embeds_many :videos
embeds_many :files
embeds_many :tags
accepts_nested_attributes_for :images, :videos, :files, :tags
validates_presence_of :title, :description, :tags
validates_uniqueness_of :title, :description
end
class Tag
include Mongoid::Document
field :tag, type: String
embedded_in :entry
embedded_in :note
end
The post route looks like this:
post '/portfolio/new' do
a = (params[:entry])
a['tags_attributes']['0']['tag'].downcase.split(", ").each_with_index{|value, index| a['tags_attributes'][index.to_s] = {"tag" => value} }
b = Entry.new(a)
b.safely.save!
redirect "portfolio/show/#{b._id}"
end
and my haml input looks like:
%label{:for => "tags"} Tags:
%input{:name => "entry[tags_attributes[0[tag]]]"}
I’m new at Ruby/Sinatra/Mongoid, so I am still trying to figure out how to access documents attributes properly.
What I am trying to do is to process the http post information and be able to (almost immediately) save it to mongodb.
The haml method for placing the input values in the right place on the hash is one I found to work through trial and error. But it doesn’t feel DRY, surely there is a better way write the embedded document? specifically entry[tags_attributes[0[tag]]] feels very akward, is there a better way of writing this?
Also in my route, in order to break the string of tags I have and store it back into the hash structure as individual embedded document before saving. I feel it’s a very round-about-way of parsing this information.
What are the best practices for dealing with this?
Haml
Route simply
Be aware on edit/put don’t forget the embedded id