#5 new
Henrik Hodne

Implement find_or_create_by

Reported by Henrik Hodne | January 29th, 2009 @ 05:12 PM

I see find_by_x is implemented (like find_by_name), but I would like find_by_x_or_create (or whatever that method is really called).

Comments and changes to this ticket

  • Henrik Hodne

    Henrik Hodne January 29th, 2009 @ 05:34 PM

    Here's a patch. I'm sorry I don't know how to make it a "real patch"

    
    # vendor/plugins/globalize2/lib/globalize/model/active_record/translated.rb
    # Around line 48
            module ClassMethods
              def method_missing(method, *args)
                if method.to_s =~ /^find_by_(\w+)$/ && globalize_options[:translated_attributes].include?($1.to_sym)
                  find(:first, :joins => :globalize_translations,
                       :conditions => [i18n_attr($1)+" = ? AND "+i18n_attr('locale')+" IN (?)",
                                       args.first,I18n.fallbacks[I18n.locale].map{|tag| tag.to_s}])
                elsif method.to_s =~ /^find_or_create_by_(\w+)$/ && globalize_options[:translated_attributes].include?($1.to_sym)
                  found = find(:first, :joins => :globalize_translations,
                       :conditions => [i18n_attr($1)+" = ? AND "+i18n_attr('locale')+" IN (?)",
                                       args.first,I18n.fallbacks[I18n.locale].map{|tag| tag.to_s}])
                   if !found
                     found = create($1.to_sym => args.first)
                   end
                   found
                else
                  super
                end
              end
    

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

The second incarnation of Globalize for Rails, which will let your Rails app speak any language on Earth, and beyond.

People watching this ticket

Pages