{S.A.Z.W.Q.A}

Entries categorized as ‘activerecord’

How to find different environment configurations in rails

October 10, 2008 · 1 Comment

While working with a multiple-database application I came across the point where I had to juggle between different environment configurations.

I had to pass connection hash to ActiveRecord::Base.establish_connection, something like this:

ActiveRecord::Base.establish_connection
(
  :adapter=>"mysql",
  :host=>"localhost",
  :username=>"myuser",
  :password=>"mypass",
  :database => "somedatabase"
)

This connection can be easily retrieved from ActiveRecord::Base.configurations, this is currently undocumented.

Using ActiveRecord::Base.configurations, the above can be simply written as:

ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['production'])

Categories: Rails · activerecord · multiple-models · rails-environments · rubyonrails
Tagged: ,

ActiveRecord : an interesting observation

September 15, 2007 · Leave a Comment

While working with ActiveRecord I observed something interesting, worth sharing.

Say we have the relation:

author has_many books

Now I create a new author say ‘a’ and a new book say ‘b’

a = Author.new
b = Book.new

Now, If I have a piece of code where I push ‘b’ into ‘a’ without saving ‘a’ first, what should happen ?

Like I do it like this:

a.books << b

see that neither ‘a’ nor ‘b’ has been saved, so what should happen? Should it give an error quoting nil id in author table or something else ?

Well things turned out to be different rather, when we push ‘b’ into ‘a’ without saving ‘a’ first, it gets pushed !

Yes, you heard it, it gets pushed.

Now everybody will wonder that how is it possible, without any id in scenario till now how the actual relationship can be handled internally ? without any id or book_id how can two records inference them ?

Well I suppose (yeah it’s completely an assumption, I haven’t read ActiveRecord source yet !) that ActiveRecord pushes the child into an array maintained by the parent and as soon as we save the parent the child gets saved and pushed automatically.

that means, when I do :

a.save

b gets saved and pushed into a.books automatically.

Waiting for comments to clear the air !

Categories: Rails · activerecord