Igor R.
Igor R.

Reputation: 15075

Getting a field having `text` type

Class Issue inherits from ActiveRecord (ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-linux], Rails 3.2.13). Within this class I attempt to perform the following select:

results = Issue.find_by_sql("select id, notes from mydb.issues;")
results.each do |r|
  puts r.notes.class.name
end

The output is NilType in every line.

The field notes is of type text (MySQL, Ver 14.14 Distrib 5.5.31, for debian-linux-gnu (x86_64) using readline 6.2). The is some text in this field, I can see it MySQL Workbench.

Why does it happen? How to access such a field correctly?

Upvotes: 0

Views: 69

Answers (4)

Igor R.
Igor R.

Reputation: 15075

Following the pointers provided by @Frederick Cheung and @Salil, I've found that Issue class has the following definition:

delegate :notes, :notes=, :to => :current_journal, :allow_nil => true

Certainly, changing the name notes in the resulting recordset solves the problem.

Upvotes: 0

mdesantis
mdesantis

Reputation: 8517

The correct way to retrieve a single column from the database is using pluck. If the following line returns false

Issue.pluck(:notes).any?{ |v| !v.nil? }
# or, since you're using MySQL:
Issue.where('notes IS NOT NULL').pluck(:notes).present?

it's likely that you have some serious problem (database connection which points to another database, f.e.)

Upvotes: 0

Rails Guy
Rails Guy

Reputation: 3866

I think you are doing it wrongly, you have already select all the notes from your table, now your results object contains all the notes in an array, so you have to only loop through it :

If you have another 'Note' model, than you have to do this :

results = Issue.find_by_sql("select * from mydb.issues;")
results.each do |r|
  puts r.notes.class.name
end

or if you have notes field in your issues table than you should do this :

results = Issue.find_by_sql("select notes from mydb.issues;")
results.each do |r|
  puts r.class.name
end

Hope it will help. Thanks

Upvotes: 0

Salil
Salil

Reputation: 47482

May be you have added notes as a attr_protected

  class Issue < ActiveRecord::Base
    attr_protected :notes
  end

  issue = Issue.new("notes" => "Some notes here")
  issue.notes # => nil

Upvotes: 1

Related Questions