Access just the value of BSON::ObjectId in ruby - ruby-on-rails

I'm working on a ruby/rails app backed by Mongodb (using Mongoid). Within the context of the Rails application everything works flawlessly but we're also accessing objects outside of the Rails environment, where I'm having trouble getting the id of an object to return as anything but a hash in the format:
{"$oid"=>"4e0005b78ba4db213500001f"}
I've figured out that I'm seeing because I'm getting back a value that's not just an id string but rather of the type BSON::ObjectId. In addition to requiring the rails environment I've also tried requiring bson explicitly in the file that's doing this work:
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require "bson"
I need to get the value simply as a string containing the id, which seems to be the default everywhere else but in this one case. Oddly this behavior only occurs in my dev environment (the rest of the guys on my team don't have this problem).
Requisite disclaimer that I'm new to Mongodb so could be missing something truly obvious.
Thanks!

You could try calling to_s on the object. In irb:
ruby-1.9.2-p180 > p = Project.last #=> #<Project _id: 4e00e77d399a46759d000002, _type: nil, version: 1, created_at: 2011-06-21 18:48:34 UTC, updated_at: 2011-06-21 18:48:34 UTC, name: "Testing MongoDB", client_id: 3, client_name: nil, group_id: 35, requestor_id: 14, requestor_name: "Test Client User", requestor_phone: "", creator_id: 2, creator_name: "Some Guy", manager_id: 23, manager_name: "Some Other Guy", manager_phone: "", manager_email: "", active: true, status: "open", default_hourly_cost: "0.0", default_hourly_charge: "0.0", default_material_markup: "0.35", add_email_internal: "", add_email_client: "", client_po_number: "", client_ticket_number: "", date_requested: nil, date_requested(1i): "2011", date_requested(2i): "6", date_requested(3i): "21">
ruby-1.9.2-p180 > p.id.to_s #=> "4e00e77d399a46759d000002"
If that doesn't work, can you post your environment.rb?

Related

Undefined method 'unshift'

I'm creating a new Rails app with Rails 6 and I want to do something like this:
#items = Item.all.unshift Item.new(id: 0, name: '-- Kein Item --')
But I get the error "undefined method `unshift' for #<ActiveRecord::Relation [#<Item id: 1, name: "Item 1", created_at: "2021-03-13 11:09:34.284978000 +0000", updated_at: "2021-03-13 11:09:34.284978000 +0000">]>"
In another Rails app I can do it, but that app is running under Rails 4.
I want to add this "empty" record so that model project hast not everytime an item and because I have somewhere Project.item.name it won't give an nil error.
Any suggestions?

Mongoid where for boolean value not working

I'm using 'mongo', '1.6.2' and 'mongoid', '2.4.11'.
I have ProPlayer model, When I run in console.
irb(main):006:0> ProPlayer.first
=> #<ProPlayer _id: 508a5549d3966f02e7000001, _type: nil, created_at: nil, updated_at: nil, first_name: "Adam", last_name: "Jones", batting_style: "R", image_thumbnail: "1.jpg", is_pro_player: true, team_id: BSON::ObjectId('508a550ad3966f02ce000012'), token_id: nil>
Here record with is_pro_player as true present but when I run where query, returns me zero records but actually there are 71 records present.
irb(main):008:0> ProPlayer.where(:is_pro_player=>true).to_a.size
=> 0
This query was working before but suddenly not working. Can anyone tell me what could be the problem?
Try the following:
ProPlayer.where(:is_pro_player.exists => true, is_pro_player: true).count
I had the same problem and I solved it by changing type from "Boolean" to "Mongoid::Boolean", then it will start putting boolean values in the db as "true" and "false" instead of "1" and "0" and "where" conditions will start working again

Why can't I destroy this variable in Ruby?

In the rails console, I do this:
input = Input.create :name => "foo"
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
Input.all
=> [#<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">]
input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
input.destroy
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> Input.all
=> []
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> input.reload
ActiveRecord::RecordNotFound: Couldn't find Input with id=8
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
What I'd really expect to see is something like:
> input
=> nil
The object is deleted from the database but the variable still exists and is still trying to point to it. What's going on?
The input variable stores a reference to the instance in memory. Destroying the record will remove the row from the database. Calling input.reload (docs) raises an exception when attempting to find the record but doesn't set the value of your variable to nil on your behalf.
This behavior can be useful in the span of a DELETE request in which you want to display information about the object you removed. For example:
class WidgetsController < ApplicationController
def destroy
#widget = Widget.find(params[:id])
#widget.destroy
respond_with #widget, notice: "You successfully removed #{#widget.name}"
end
end
The destroy method makes the SQL call to the database and destroys the row in the table that contains it. It does still allow you to manipulate the object in the application as long as it’s still in scope (i.e) the callbacks and
filters are allowed even after destroying the object.
It is better to use "delete" if we don't want the callbacks to be triggered or if we want better performance
you can use input.delete

The mongoid function "update_attribute" causes all attributes to be re-ordered alphabetically

Following up on this 1 year old post:
Mongodb mongoid model attributes sorted by alphabetical order not insertion order
I have a rails 3.2.8 application that uses mongoid v. 3.0.0. My application occasionally uses the "update_attribute" function on a database object (e.g. a product), but when it does all attributes gets reordered alphabetically.
When I duplicate this in the console, it looks like this:
1.9.3-p385 :001 > product = Product.find("5156bc9b83c3368121000008")
=> [#<Product _id: 5156bc9b83c3368121000008, _type: nil, product_number: "123", product_name: "Some product name", long_description: "<P>Some long product description.</P>", vendor_number: "abc", language_i_d: "1234", currency_i_d: "USD", category_number: "1", image_link: "http://some-external-website.com/image-path.jpg", original_id: "123456">]
1.9.3-p385 :002 > product.update_attribute(:image_link, "http://my-own-website.com/image-path.jpg")
=> true
1.9.3-p385 :003 > exit
I now fire up the console again (for some reason I need to exit and re-open the console before the new order is displayed):
1.9.3-p385 :001 > product = Product.find("5156bc9b83c3368121000008")
=> [#<Product _id: 5156bc9b83c3368121000008, _type: nil, category_number: "1", currency_i_d: "USD", image_link: "http://my-own-website.com/image-path.jpg", language_i_d: "1234", long_description: "<P>Some long product description.</P>", original_id: "123456", product_name: "Some product name", product_number: "123", vendor_number: "abc">]
Does anyone know how to avoid this reordering?
This isn't mongoid's fault. If an update causes a document to grow and mongo had to move the document as a result then mongodb itself may reorder the document's fields (see docs and a jira issue where this is described as normal)

Rails to_json method: problems with unicode characters

I'm having troubles with unicode characters in my Rails app. The problem is that when I store the object with some string containing scandinavian characters, those characters then are not rendered correctly when using to_json method. Basically all those characters are rendered like this:
\"description\":\"\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"
Here is example:
Item.create(:title => "Test title", :description => "With scandic characters öäöäö")
=> #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters öäöäö", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false>
At this point the created object looks ok.
Item.last
returns
=> #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters \xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4\xC3\xB6", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false>
This "With scandic characters \xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4\xC3\xB6" - does it still look ok? Or do I miss some proper encoding already at the item creation stage?
Anyway, now when call Item.last.to_json, I get this:
"description\":\"With scandic characters \\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"
And at this point the string is definitely broken.
I'm lacking some knowledge about the proper characters encoding in Rails, so any hints would be appreciated. The item, however, looks fine when rendered in the browser - this happens only when doing a JSON response.
Ok, the issue was that MySQL db was not in unicode. This is fixed now by migrating to PosgreSQL, ensuring it is in unicode and using Taps gem to migrate the data. All according to this Railscast: http://railscasts.com/episodes/342-migrating-to-postgresql

Resources