On Sunday 10 May 2009, Jian Lin wrote:
> i was doing it like this:
>
>
> all_phrases = frequencies.keys
> Phrase.transaction do
> all_phrases.each do |phrase|
> recordPhrase = Phrase.new(:s => phrase, :frequency =>
> frequencies[phrase], :length => lengths[phrase])
> recordPhrase.save
> end
> end
Consider
Phrase.transaction do
frequencies.each do |phrase, freq|
Phrase.create!(:s => phrase, :frequency => freq)
end
end
Hash#each passes keys and values to your block and avoids unnecessary
lookups.
My snippet above doesn't take into account your :length =>
lengths[phrase] and that is as it should be. Presumably, lengths[phrase]
== phrase.length. Then
class Phrase < ActiveRecord::Base
attr_protected :length
...
def s=(value)
self.length = value.length
end
end
would be much cleaner code because it puts responsibility for setting
the length attribute where it belongs.
Michael
--
Michael Schuerig
mailto:[email protected]
http://www.schuerig.de/michael/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---