Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing record being validated to error message generator #24119

Merged
merged 1 commit into from
Apr 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions activemodel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
* Allow passing record being validated to the message proc to generate
customized error messages for that object using I18n helper.

*Prathamesh Sonpatki*

## Rails 5.0.0.beta3 (February 24, 2016) ##

* No changes.
Expand Down
3 changes: 2 additions & 1 deletion activemodel/lib/active_model/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,8 @@ def generate_message(attribute, type = :invalid, options = {})
default: defaults,
model: @base.model_name.human,
attribute: @base.class.human_attribute_name(attribute),
value: value
value: value,
object: @base
}.merge!(options)

I18n.translate(key, options)
Expand Down
8 changes: 8 additions & 0 deletions activemodel/test/cases/validations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -444,4 +444,12 @@ def test_dup_validity_is_independent
assert topic.invalid?
assert duped.valid?
end

def test_validation_with_message_as_proc_that_takes_a_record_as_a_parameter
Topic.validates_presence_of(:title, message: proc { |record| "You have failed me for the last time, #{record.author_name}." })

t = Topic.new(author_name: 'Admiral')
assert t.invalid?
assert_equal ["You have failed me for the last time, Admiral."], t.errors[:title]
end
end