grosser / translated_attributes

AR/Rails translatable attributes through virtual fields
9 stars 2 forks source link

Translation model through association not always loaded #2

Open philly-mac opened 12 years ago

philly-mac commented 12 years ago

Hi,

There is an issue that randomly happens in the method

    def store_translated_attributes
      return true unless @translated_attributes_changed
      translations.delete_all
      @translated_attributes.each do |locale, attributes|
        attributes.each do |attribute, value|
          next if value.blank?
          next unless self.class.translated_attributes_options[:fields].include? attribute.to_sym
          translations.create!(translated_attributes_options[:attribute_column] => attribute, :text=>value, :language=>locale)
        end
      end
      @translated_attributes_changed = false
      true
    end

the line

          translations.create!(translated_attributes_options[:attribute_column] => attribute, :text=>value, :language=>locale)

throws the error

unknown attribute: attribute

This seems to be because the translation model through the association is not loaded yet. Doing a

translations.new

fixes the problem.

So could I suggest a fix like this

          translation = translations.new
          translation.attributes = {translated_attributes_options[:attribute_column] => attribute, :text => value, :language => locale}
          translation.save!

This solves the problem by doing the load of the model through the association and stops the error from happening.

If you have a better idea of how to fix this could you let me know, or even better implement it so I could do a pull of the new code?

Thanks

grosser commented 12 years ago

Thats some weird issue you got there oO

how about translations.build(attributes).save!

or forcing the load of the translation model by just placing it infront of the translated_attributes call ?