Mongoid where for boolean value not working - ruby-on-rails

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

Related

Ruby validation passes in console, fails in rake task

This is my EmailContact model:
class EmailContact < ActiveRecord::Base
validates :email, :presence => true, :email => true
end
I am using the ruby gem valid_email.
I run the following in my rails console, in the same environment as my rake task I will show later:
>> email_contact = EmailContact.new(:email => 'a253545#gmail.com')
>> email_contact.valid?
true
So, as you can see, in the rails console I am building an EmailContact and it is valid.
Then I run this in my rake task:
list_entity = {:branch=>"Nashua Branch-YMCA of Greater Nashua", :branch_id=>"485", :call_type=>nil, :client_id=>"2264", :client_name=>"YMCA of Greater Nashua", :date_of_birth=>nil, :email=>"a253545#gmail.com", :first_name=>"Sridhar", :last_name=>"Tipirneni", :list_entity_id=>"277795", :mem_id=>"4085008", :mem_unit_id=>"2138728", :member_id=>"0213262-01", :membership_type=>"Dual 2 Adult Family", :membership_type_id=>"5203", :most_recent_join_date=>nil, :old_membership_type=>nil, :phone_number=>"(970)456-1010", :primary_language=>"English", :termination_date=>nil, :termination_reason=>nil, :unit_id=>"0213262", :unit_type=>nil, :visits=>nil, :"#i:type"=>"c:NpsListEntityDto"}
email_contact = EmailContact.new(list_entity.except(:"#i:type"))
puts email_contact.valid?
This returns false. The only validation, at all, is the email. Why does this email validate successfully in my console but fail in my rake task?
FYI, when I remove :email => true from my EmailContact model and only validate the presence of an :email, they both work fine. So the issue is definitely within the :email => true piece of my validation, but I don't understand why it passes in one place and fails in another.
EDIT
In my console, my model looks like this when using the full list_entity:
#<EmailContact id: nil, branch: "Nashua Branch-YMCA of Greater Nashua", branch_id: 485, call_type: nil, client_id: 2264, client_name: "YMCA of Greater Nashua", date_of_birth: nil, email: "a253545#gmail.com", first_name: "Sridhar", last_name: "Tipirneni", list_entity_id: 277795, mem_id: "4085008", mem_unit_id: "2138728", member_id: "0213262-01", membership_type: "Dual 2 Adult Family", membership_type_id: 5203, most_recent_join_date: nil, old_membership_type: nil, phone_number: "(970)456-1010", primary_language: "English", termination_date: nil, termination_reason: nil, unit_id: "0213262", visits: nil, loaded_at: nil, failed_at: nil, unit_type: nil, created_at: nil, updated_at: nil, list_id: nil>
In my rake task, when I run email_contact.inspect, this is returned:
#<EmailContact id: nil, branch: "Nashua Branch-YMCA of Greater Nashua", branch_id: 485, call_type: nil, client_id: 2264, client_name: "YMCA of Greater Nashua", date_of_birth: nil, email: "a253545#gmail.com", first_name: "Sridhar", last_name: "Tipirneni", list_entity_id: 277795, mem_id: "4085008", mem_unit_id: "2138728", member_id: "0213262-01", membership_type: "Dual 2 Adult Family", membership_type_id: 5203, most_recent_join_date: nil, old_membership_type: nil, phone_number: "(970)456-1010", primary_language: "English", termination_date: nil, termination_reason: nil, unit_id: "0213262", visits: nil, loaded_at: nil, failed_at: nil, unit_type: nil, created_at: nil, updated_at: nil, list_id: nil>
As you can see, they are both the exact same - The console model is valid, the rake model is invalid.
EDIT 2
I am using the valid_email gem, mentioned above. Here is the filepath:
/Users/luigi/.rvm/gems/ruby-2.0.0-p247#hub/gems/valid_email-0.0.4/lib/valid_email/email_validator.rb
All of my other gems are stored here as well it seems like.
It may also be worth mentioning that I get this warning before the validation fails:
[deprecated] I18n.enforce_available_locales will default to true in
the future. If you really want to skip validation of your locale you
can set I18n.enforce_available_locales = false to avoid this message.
20 hours later, I found the issue.
Using savon, all of the strings returned in my hash were being converted to a datatype of Nori::StringWithAttributes. The encoding was the same (UTF-8), but the class was different.
Running email_contact.email = email_contact.email.to_s prior to checking if the model is valid solves the issue.

rails yaml fixture - specify NULL value

I have a fixture with values like this:
product_four:
id: 4
application_id: 1
title: "oldtitle"
deleted_at: ~
Setting up a postgresql database for testing.
But I can't figure out how to set the deleted_at field to NULL rather than [empty].
I've tried:
deleted_at: :null
deleted_at: <%= nil %>
deleted_at: ~
deleted_at: NULL
And probably a couple more, without luck.
Clues for the clueless?
Just leave the value out:
product_four:
id: 4
application_id: 1
title: "oldtitle"
deleted_at:
For example:
> {:k => ''}.to_yaml
=> "--- \n:k: \"\"\n"
> {:k => nil}.to_yaml
=> "--- \n:k: \n"
> YAML.load({:k => nil}.to_yaml)
=> {:k=>nil}
Note that k: means that k has a nil value whereas k: "" means that k has an empty string as its value.
You could also use an explicit null if all your parsers are aware of the latest YAML spec:
product_four:
id: 4
application_id: 1
title: "oldtitle"
deleted_at: null
For example:
> YAML.load("--- \n:k: null\n")
=> {:k=>nil}

Access just the value of BSON::ObjectId in ruby

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?

Error with "to_sql" on Rails 3 Beta 4

I'm testing Rails 3 beta 4 on Ruby 1.9.2-head, and when I start a
console and do:
Game.first.to_sql
I get this error:
ArgumentError: wrong number of arguments (0 for 1)
I know it can find the Game record, because when I type:
Game.first
it returns:
=> #<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37",
updated_at: "2010-06-19 11:02:37">
What am I missing? I just want to make the to_sql work in a very simple
case.
.
When you run Game.first you are returning a Game object, not a ActiveRecord::Relation object as you are expecting.
To do what you're trying to do, you'll need to do:
Game.limit(1).to_sql
This lets you run it without to_sql and return the object as you expected it, although it will be in an array, which then you can run .first on it like you wanted anyways.
irb(main):004:0> Game.limit(1).to_sql
=> "SELECT `games`.* FROM `games` LIMIT 1"
irb(main):005:0> Game.limit(1).class
=> ActiveRecord::Relation
irb(main):006:0> Game.limit(1)
=> [#<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37", updated_at: "2010-06-19 11:02:37">]
irb(main):007:0> Game.limit(1).first
=> #<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37", updated_at: "2010-06-19 11:02:37">
When you dig into the source, when you run .first on an ActiveRecord::Relation it runs the following (which is the same as I showed you):
def find_first
if loaded?
#records.first
else
#first ||= limit(1).to_a[0]
end
end

Rails: class' object_id changes after I make a request

I really can't explain this behavior, notice how after I make a request the class' object id has changed, and therefore my is_a? evaluation returns false.
any ideas? I'm not even sure how to debug this. Also, this isn't related to making a request from the command line. The same behavior is exhibited on the web server as well, it's just easier to explain from the command line.
staging$ RAILS_ENV=staging script/console
Loading staging environment (Rails 2.3.2)
>> c = CartItem.new
=> #<CartItem id: nil, order_id: nil, order_source: nil, date: nil, user_id: nil, created_at: nil, updated_at: nil, paid: nil, payment_id: nil, values: nil, cart_description: nil, type: nil, price: nil, email: nil, error: nil>
>> c.class.object_id
=> 70151495336400
>> CartItem.object_id
=> 70151495336400
>> c.is_a? CartItem
=> true
>> app = ActionController::Integration::Session.new
=> #<ActionController::Integration::Session:0x7f9ad5c55db0 .... >
>> app.get("site/favorite")
=> 200
>> c.class.object_id
=> 70151495336400
>> CartItem.object_id
=> 70151496019760
>> c.is_a? CartItem
=> false
>> c.class
=> CartItem(id: integer, order_id: string, order_source: string, date: date, user_id: integer, created_at: datetime, updated_at: datetime, paid: boolean, payment_id: integer, values: text, cart_description: string, type: string, price: integer, email: string, error: string)
Every new context (request/response cycle) will regenerate the object IDs. You may want to use responds_to?, instead of is_a?.
Since the ActionController::Integration module is used for integration testing, getting a url reloads your classes, therefore redefining the CartItem identifier. You now basically have two CartItem classes, one hanging around on your stack without an identifier pointing to it anymore (the "old one") and one referenced by the CartItem identifier.

Resources