Skip to content

Instantly share code, notes, and snippets.

@ilpoldo
Created February 8, 2011 16:15
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 ilpoldo/816672 to your computer and use it in GitHub Desktop.
Save ilpoldo/816672 to your computer and use it in GitHub Desktop.
class Sentence < ActiveRecord::Base
has_many :translations
accepts_nested_attributes_for :translations, :allow_destroy => true, :reject_if => proc { |obj| obj[:text].blank? }
end
require 'spec_helper'
describe Sentence do
it "validates translation language" do
s = Sentence.new({
:language => 'en',
:text => 'hello world',
:translations_attributes => {
"0" => {:language => 'it', :text => 'ciao mondo'},
"1" => {:language => 'fr', :text => 'bonjour monde'}
}
})
s.save
end
end
## The test errors out when saving the record:
# => undefined method `language' for nil:NilClass
class Translation < ActiveRecord::Base
belongs_to :sentence
validate :disallow_same_language_translations
def disallow_same_language_translations
# self.sentence returns nil even if sentence 'accepts_nested_attributes_for :translations'
if self.sentence.language == self.language
errors.add(:language, 'You can\'t add a translation in the same language as the source')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment