Skip to content

Instantly share code, notes, and snippets.

@sbleon
Created August 8, 2011 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbleon/1131061 to your computer and use it in GitHub Desktop.
Save sbleon/1131061 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'logger'
require 'pp'
puts "Active Record #{ActiveRecord::VERSION::STRING}"
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:host => '127.0.0.1',
:user => 'root',
:database => 'test'
)
ActiveRecord::Schema.define do
create_table :comments, :force => true do |t|
t.integer :post_id
end
create_table :posts, :force => true do |t|
end
end
class Post < ActiveRecord::Base
end
class Comment < ActiveRecord::Base
belongs_to :post
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
Comment.joins(:post).where('posts.id IS NOT NULL').update_all({:post_id => 1}, nil, {:limit => 1, :order => "posts.id"})
# This should produce something like the following in the log output:
# UPDATE comments SET "post_id" = 1 WHERE (comments.id IN (SELECT id from (SELECT "comments".* FROM "comments" INNER JOIN "posts" ON "posts"."id" = "comments"."post_id" WHERE (posts.id IS NOT NULL) ORDER BY posts.id LIMIT 1) x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment