Mongomapper human readable id - ruby-on-rails

Is there any way to create human readable id for mongomapper
I mean replace 54114ac51d41c84fb900005a to id 1
Thanks

Try:
gem 'mongomapper_id2'
It’s a MongoMapper’s plugin to add auto incremented ids in MongoMapper’s documents.
Example:
# app/models/movie.rb
class Movie
include MongoMapper::Document
key :title, String
# Here is the mongomapper_id2
auto_increment!
end
movie = Movie.create(:title => 'The Simpsons Movie')
movie.id # BSON::ObjectId('4d1d150d30f2246bc6000001')
# Here is the mongomapper_id2
movie.id2
# => 1
movie2 = Movie.create(:title => 'Pirates of Silicon Valley')
movie2.id2
# => 2

Related

How to perform morphology analysis in RoR?

I am looking for ways to turn single words to their infinitives inside models:
cats -> cat
sharpest -> sharp
etc.
Do you know of any gems or libraries that are able to do that?
String#singularize is providing : The reverse of pluralize, returns the singular form of a word in a string.
'posts'.singularize # => "post"
'octopi'.singularize # => "octopus"
'sheep'.singularize # => "sheep"
'word'.singularize # => "word"
'the blue mailmen'.singularize # => "the blue mailman"
'CamelOctopi'.singularize # => "CamelOctopus"
'leyes'.singularize(:es) # => "ley"
for String#pluralize : Returns the plural form of the word in the string.
'post'.pluralize # => "posts"
'octopus'.pluralize # => "octopi"
'sheep'.pluralize # => "sheep"
'words'.pluralize # => "words"
'the blue mailman'.pluralize # => "the blue mailmen"
'CamelOctopus'.pluralize # => "CamelOctopi"
'apple'.pluralize(1) # => "apple"
'apple'.pluralize(2) # => "apples"
'ley'.pluralize(:es) # => "leyes"
'ley'.pluralize(1, :es) # => "ley"
In addition you can also have a look at 'verbs' gem
Conjugates most common english verbs for all persons, tenses, standard
aspects, and modern moods (with active diathesis). Standard and
exceptional spelling rules are obeyed.

How to use $in operator in embed document

I'm new to MongoID. I have following models:
class Vehicle
include Mongoid::Document
include Mongoid::Timestamps
##
# Relationship
embeds_one :specification
end
class Specification
include Mongoid::Document
##
# Columns
field :body, type: String
##
# Relationship
embedded_in :vehicle
end
In my controller I'm trying to use $in operator in body field of specification /embed document/. How to use $in operator in embed document? I tried below code but it's not work.
result += Vehicle.where(:specification.matches => { :body.in => param(:body) }) if params[:body].present?
Thank you for help :)
as #mu-is-too-short mentioned in his comment, to search in embedded docs you use
if params[:body].present?
result += Vehicle.where('specification.body' => param(:body)).to_a
end
please note that Vehicle.where(...) returns a Criteria which is not the objects only the query to be evaluated.
also note that if you want to use specific operators like in, <, <= you have to use the corresponding mongodb operator for example
Vehicle.where('specification.body' => {'$in' => param(:body)}) # matches .in
Vehicle.where('specification.body' => {'$lt' => param(:body)}) # matches <
Vehicle.where('specification.body' => {'$lte' => param(:body)}) # matches <=

Active Record without Rails: How to pass an Arbitrary hash to Active Record

I'm trying to pass the following Hash to Active Record to save:
[{
"id"=>"WSECOUT",
"realtime_start"=>"2013-02-10",
"realtime_end"=>"2013-02-10",
"title"=>"Reserve Bank Credit - Securities Held Outright",
"observation_start"=>"1989-03-22",
"observation_end"=>"2013-02-06",
"frequency"=>"Weekly, Ending Wednesday",
"frequency_short"=>"W",
"units"=>"Billions of Dollars",
"units_short"=>"Bil. of $",
"seasonal_adjustment"=>"Not Seasonally Adjusted",
"seasonal_adjustment_short"=>"NSA",
"last_updated"=>"2013-02-08 08:32:33-06",
"popularity"=>"42",
"notes"=>"The amount of securities held by Federal Reserve Banks. This quantity is the cumulative result of permanent open market operations: outright purchases or sales of securities, conducted by the Federal Reserve. Section 14 of the Federal Reserve Act defines the securities that the Federal Reserve is authorized to buy and sell."
}]
My ruby class looks like this:
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:username => "root",
:password => "*********",
:database => "fred"
)
class Series < ActiveRecord::Base
attr_accessible :id, :realtime_start, :realtime_end, :title, :observation_start,
:observation_end, :frequency, :frequency_short, :units, :units_short,
:seasonal_adjustment, :seasonal_adjustment_short, :last_updated,
:popularity, :notes
end
require_relative 'wsecout'
#series = Wsecout.new.getSeries "wsecout"
#series = #series['series']
test = Series.create(#series)
The #series variable contains the Hash. When I run this code, the object is created as is the row in mysql, however, there is no data in the fields. I know I'm missing a step here, but I am unable to figure out which step. Also, is there going to be a problem with my Hash containing an id, because Active Record creates it's own id?
Answer to your second question "map that "id" to a new field called :series_id":
#series['series'][0]['series_id'] = #series['series'][0]['id']
#series['series'][0].delete('id')
Or if you want to change multiple keys based on some criteria, then use it in the if condition as below:
#series['series'][0].keys.each do |k|
if(k == 'id')
#series['series'][0]['series_id'] = #series['series'][0][k]
#series['series'][0].delete(k)
end
end
This will iterate through each key of the hash and if the key matches to id then it add another key series_id with the same value and delete the id.

RoR: ActiveScaffold: How can I make update_column fetaure conditional?

Schema:
action_types
------------
id
name
description
actions
-------
id
action_type_id
date
description
The goal is to copy action_types.description to actions.description only if it is not occupied yet on the UI (!).
What is done:
class ActionsController < ApplicationController
active_scaffold :action do |c|
c.columns = [ \
, :date \
, :action_type \
, :description \
]
c.columns[:action_type].form_ui = :select
c.columns[:action_type].options[:update_column] = :description
c.columns[:description].form_ui = :textarea
c.columns[:description].options = { :cols => 40, :rows => 5}
end
protected
def after_render_field(record, column)
# record: almost empty, only "action_type" is filled.
# column: column.name == "action_type"
# #params[]: id: id for the record
# But no data on UI state. So if the user wrote some lines into the
# description then it will be lost. No possibility
# to express "do nothing!"
end
#...
end
Alternatively I can accept if we do not have this functionality during "update" only on "create". Which is a half measure, but will be enough for now.
Any ideas?
(Rails 2.3.4)
Up-vote and accept for them:
http://markmail.org/message/cfbhmeyfjw3bjisp#query:+page:1+mid:vnnrbzdj7cywlvgm+state:results
You can copy javascript_for_update_column method into your helper file, and change :with to "Form.serialize(this.form)" (from "'value=' + this.value").
In after_render_field method you can use:
update_record_from_params(record, active_scaffold_config.update.columns, params[:record])
FYI: Empty fields are coming as nils, not empty strings.

How to implenent mongodb 'includes?' finder condition

I am using Mongoid and have a project and a user model.
in the Project model, I have a field
class Project
include Mongoid::Document
field :name
field :user_ids, :type => Array
end
class User
include Mongoid::Document
field :email
end
I can find all the users belonging to one project, i.e., 'find this project's users'
#project = Project.first # => 'Housework'
User.criteria.id(#project.user_ids) # => ['Bart','Lisa','Maggie']
But I am having a bit trouble finding all the projects belonging to one user, i.e, 'find this user's projects'
#user = User.first # => 'Bart'
Project.where(:user_ids => #user.id) # doesn't work
Project.where(:user_ids.includes => #user.id) # not such method
Project.where(:user_ids => [#user.id]) # doesn't make sense to compare arrays, but tried anyway and doesn't work
I know that you can have another field in the User model to store project_ids, I would gladly do that, but I am just curious, is there a method to be used in finder conditions that works similarly to #includes? in ruby?
I found a solution to this. it is the all_in finder method
example:
Fruit.all[0].colors = ['red','green','blue'] #=> apple
Fruit.all[1].colors = ['yellow','green'] #=> banana
Fruit.all[2].colors = ['red', 'yellow'] #=> pineapple
To find all fruits that have the color red in their 'colors' array field, one can query:
Fruit.all_in(:colors => ['red'])
=>[apple, pineapple]

Resources