views:

41

answers:

3

I have the following script

ActiveRecord::Base.establish_connection(:adapter => 'mysql', :database => 'development', :username => 'appAccount', :password => '------', :socket => '/tmp/mysql.sock')

class ProcessQueue < ActiveRecord::Base
end

The tutorial I'm using claims the following should work.

updateQ = ProcessQueue.find(:all, :conditions => "photoID = '234'")
updateQ.ExIfQ = 1
updateQ.save

updateQ has the following data

ProcessQueue id: 104, photoID: 234, ExIfQ: 0, Providor: 0, created_at: "2009-12-30 14:42:01", updated_at: "2009-12-30 14:42:01"

But when running updateQ.ExIfQ = 1 I get an error saying the method does not exist

NoMethodError: undefined method 'ExIfQ=' for #<Array:0x102207c60>

The error makes sense. I'm trying to make a change on an array. Therefore I can only assume either I'm wrong or the tutorial is wrong :)

I was wondering if someone could tell me how I should be making this update?

p.s this is a background script running in my rails application.

Thanks

A: 

If there is only going to be one of these that is a query result, use:

updateQ = ProcessQueue.find(:first, :conditions => "photoID = '234'")
MattMcKnight
i do not understand the down-vote. In the OP code, if you replace :all by :first, as mentioned in this answer, the code will work.
nathanvda
+1  A: 

find method returns array of objects.

You can add first:

updateQ = ProcessQueue.find(:all, :conditions => "photoID = '234'").first

and then your example will work, or iterate over array

updateQ = ProcessQueue.find(:all, :conditions => "photoID = '234'")
updateQ.each do |u|
  up.ExIfQ = 1
  up.save
end
klew
+1  A: 

There's a few approaches to this that work, each with their various quirks.

The quick and dirty method is to use update_all to reassign the attribute:

ProcessQueue.update_all('ExIfQ=1', :photoID => 234)

Iterate over all those found using find:

ProcessQueue.find(:all, :conditions => { :photoID => 234 }).each do |pq|
  pq.ExIfQ = 1
  pq.save!
end

Find one and manipulate it directly:

if (pq = ProcessQueue.find_by_photoID(234))
  pq.ExIfQ = 1
  pq.save!
end

As a note, try not to spell out your conditions when declaring them using array with placeholders or hash-style. It's much safer since it will do the type conversion for you, as required.

tadman