DEV: pluck_first

Doing .pluck(:column).first is a very common pattern in Discourse and in
most cases, a limit cause isn't being added. Instead of adding a limit
clause to all these callsites, this commit adds two new methods to
ActiveRecord::Relation:

pluck_first, equivalent to limit(1).pluck(*columns).first

and pluck_first! which, like other finder methods, raises an exception
when no record is found
This commit is contained in:
Daniel Waterworth
2019-10-21 11:32:27 +01:00
parent 72822aa93f
commit 55a1394342
43 changed files with 99 additions and 80 deletions

View File

@ -98,19 +98,19 @@ describe Wizard::StepUpdater do
expect(SiteSetting.site_contact_username).to eq(user.username)
# Should update the TOS topic
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("<eviltrout@example.com> template")
# Can update the TOS topic again
updater = wizard.create_updater('contact', contact_email: 'alice@example.com')
updater.update
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("<alice@example.com> template")
# Can update the TOS to nothing
updater = wizard.create_updater('contact', {})
updater.update
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("<contact_email> template")
expect(wizard.completed_steps?('contact')).to eq(true)
@ -145,7 +145,7 @@ describe Wizard::StepUpdater do
expect(SiteSetting.city_for_disputes).to eq("Fairfield, New Jersey")
# Should update the TOS topic
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("ACME, Inc. - New Jersey law - Fairfield, New Jersey template")
# Can update the TOS topic again
@ -154,13 +154,13 @@ describe Wizard::StepUpdater do
governing_law: 'California law',
city_for_disputes: 'San Francisco, California')
updater.update
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("Pied Piper Inc - California law - San Francisco, California template")
# Can update the TOS to nothing
updater = wizard.create_updater('corporate', {})
updater.update
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck(:raw).first
raw = Post.where(topic_id: SiteSetting.tos_topic_id, post_number: 1).pluck_first(:raw)
expect(raw).to eq("company_name - governing_law - city_for_disputes template")
expect(wizard.completed_steps?('corporate')).to eq(true)