Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

[3.1.0.rc5] ActiveRecord doesn't find record created with CSV info #2352

Closed
nathanborgo opened this Issue · 4 comments

2 participants

@nathanborgo

When creating a record from a CSV file, Record.find_by doesn't find them. This might not have anything to do with creating records from a file, but that's how I ran into the problem.

Demo apps: https://github.com/subtractiv/Rails-ActiveRecord-3.1.0.rc5-Issue

The app using 3.0.9 works as expected.

Action in question:

def create
  file = params[:record][:file].tempfile

  CSV.foreach file, :headers => true, :header_converters => :symbol do |row|
    Record.create row.to_hash
  end

  redirect_to records_url
end

Examples from rails console:

> Record.find_by_email "matching@asd.asd"
=> nil     # Should return record created through the CSV file

> Record.create :email => "matching@asd.asd"
> Record.find_by_email "matching@asd.asd"
=> <Record id: 4, email: "matching@asd.asd">
> Record.find_all_by_email "matching@asd.asd" 
=> [<Record id: 4, email: "matching@asd.asd">]    # Should return both

Output from debugging row.to_hash:

{:email=>"Matching@asd.asd", :first_name=>"First", :last_name=>"Last"}
{:email=>"Notmatching@asd.asd", :first_name=>"Matching", :last_name=>"Name"}
{:email=>"asdasdasdasd@asd.asd", :first_name=>"asd", :last_name=>"asd"}

Output from querying the database directly:

sqlite> SELECT "records".* FROM "records" WHERE "records"."email" = 'Matching@asd.asd' LIMIT 1;
# This one should have returned the CSV record, but it returns nothing
sqlite> SELECT "records".* FROM "records" WHERE "records"."email" = 'nomatch@asd.asd' LIMIT 1;
5|2|match|this|nomatch@asd.asd|2011-07-29 17:13:13.821972|2011-07-29 17:13:13.821972

Hopefully that's enough information for now. If I missed something, let me know.

@tenderlove
Owner

Hi, are you using Ruby 1.9?

@nathanborgo

Yea, I'm on 1.9.

@tenderlove
Owner

Check the encoding of the strings you're inserting:

p row.to_hash.values.map(&:encoding)

If they are marked as binary, sqlite will store them as blobs. You should either tell the CSV reader the input encoding, or change your strings encoding to UTF-8.

@tenderlove tenderlove closed this
@nathanborgo

Well that was anticlimactic. It was an encoding issue, after all. Everything works fine after forcing UTF-8.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.