Rails: class' object_id changes after I make a request - ruby-on-rails

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.

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.

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

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

time type field getting bad default datetime if it is invalid

Terrible title, but this is what I have:
Loading development environment (Rails 3.2.8)
1.9.3p194 :001 > Product
=> Product(id: integer, name: string, date: datetime, created_at: datetime, updated_at: datetime, end_time: datetime, start_time: time)
1.9.3p194 :002 > p = Product.new
=> #<Product id: nil, name: nil, date: nil, created_at: nil, updated_at: nil, end_time: nil, start_time: nil>
1.9.3p194 :003 > p.start_time = "foo"
=> "foo"
1.9.3p194 :004 > p.start_time
=> 2000-01-01 00:00:00 UTC
I wouldn't expect an invalid time to parse into a valid one. This is causing me issues with validations from form submissions.
This is somewhat related: Rails 3 - Validation for Time existence
And leads to this issue in github: https://github.com/rails/rails/issues/6045
I tried eye tracing the code, but nothing pops out at me except that the "foo" shouldn't parse and it should return nil.
EDIT: I created a sample app that displays this exact behavior https://github.com/danbeaulieu/test-app
But really it's just a bare bones app with a single model.
You can use validates_timeliness which validates dates, times and datetimes .
Then in your model you can do
validates_time :start_time
OR have a look at my GIST to handle default date validation

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

Resources