hi. guys,
I have finally learnt how to use script/runner and have written a
script with the intention of updating the status attribute of my
“Blog” objects every 24 hours to “published”.
I have written a script (which I will paste below).
I seem to always get the error below which relates to
ActiveRecord::ReadOnlyRecord when I try to save/update the object.
“projects/myApp/vendor/rails/activerecord/lib/active_record/base.rb:
2867:in `create_or_update’: ActiveRecord::ReadOnlyRecord
(ActiveRecord::ReadOnlyRecord)”.
Here is the script:
=============== Start ===============
class Blog < ActiveRecord::Base
new_blogs = Blog.status_name_does_not_equal_all([‘live’,
‘archived’])
live_status = Status.find_by_name(‘live’)
new_blogs.each do |new_blog|
new_blog.status = live_status
new_blog.save(false)
new_blog.update_attribute(status, live_status)
end
end
=============== End ===============
Reading from http://api.rubyonrails.org/ under the doc for “find”, I
do understand that the :readonly flag is set ONLY if “:joins” was
specified. In my case, I had never done so.
I used “updates” and that failed. Read Don't Use ActiveRecord::Base.update - Dan Manges's Blog
and found that I have to use update_attributes but in this case, I
have already set my “status” using the new status object (ie.
new_blog.status = live_status )
I then tried using save/save! (in desperation) and fell flat on my
face with an error.
When I update objects in my rails app, it’s all fine but when I run a
script through script/runner, I constantly get this ReadOnly error.
When I run pretty much the same thing on script/console, the Blog
record happily gets updated without a hick. Here’s an extract:
==================Extract from script/console - start
new_blog = Blog.find_by_title(‘test1’)
=> #<Blog id: 19, user_id: 1, status_id: 2, title: “test1”,
description: “4A63 forever!”, location: “bayswater”, contact_name:
“Jimi Hendrix”, contact_number
: “01233993933”, condition: “233223”, new: false, sold: false,
created_by: “admin”, updated_by: “admin”, created_at: “2010-04-06
06:57:04”, updated_at: “2010
-04-06 06:59:31”>
new_blog.title
=> “test1”
new_status = Status.find_by_name(‘live’)
=> #<Status id: 5, name: “live”, display_title: “live”, created_by:
“admin”, updated_by: “admin”, created_at: “2010-03-15 12:17:14”,
updated_at: “2010-03-15
12:17:14”>
new_status.name
=> “live”
new_blog.status = new_status=> #<Status id: 5, name: “live”, display_title: “live”, created_by: “admin”, updated_by: “admin”, created_at: “2010-03-15 12:17:14”, updated_at: “2010-03-15
12:17:14”>
new_status=> #<Status id: 5, name: “live”, display_title: “live”, created_by: “admin”, updated_by: “admin”, created_at: “2010-03-15 12:17:14”, updated_at: “2010-03-15
12:17:14”>
new_blog.save
=> true
==================Extract from script/console - end
Any ideas?
thanks