Perform the where(...).first to find_by(...) refactoring.

This refactoring was automated using the command: bundle exec "ruby refactorings/where_dot_first_to_find_by/app.rb"
This commit is contained in:
Louis Rose 2014-05-06 14:41:59 +01:00
parent f1369e4503
commit 1574485443
104 changed files with 204 additions and 213 deletions

View File

@ -5,7 +5,7 @@ class Admin::ApiController < Admin::AdminController
end end
def regenerate_key def regenerate_key
api_key = ApiKey.where(id: params[:id]).first api_key = ApiKey.find_by(id: params[:id])
raise Discourse::NotFound.new if api_key.blank? raise Discourse::NotFound.new if api_key.blank?
api_key.regenerate!(current_user) api_key.regenerate!(current_user)
@ -13,7 +13,7 @@ class Admin::ApiController < Admin::AdminController
end end
def revoke_key def revoke_key
api_key = ApiKey.where(id: params[:id]).first api_key = ApiKey.find_by(id: params[:id])
raise Discourse::NotFound.new if api_key.blank? raise Discourse::NotFound.new if api_key.blank?
api_key.destroy api_key.destroy

View File

@ -27,13 +27,13 @@ class Admin::UsersController < Admin::AdminController
end end
def show def show
@user = User.where(username_lower: params[:id]).first @user = User.find_by(username_lower: params[:id])
raise Discourse::NotFound.new unless @user raise Discourse::NotFound.new unless @user
render_serialized(@user, AdminDetailedUserSerializer, root: false) render_serialized(@user, AdminDetailedUserSerializer, root: false)
end end
def delete_all_posts def delete_all_posts
@user = User.where(id: params[:user_id]).first @user = User.find_by(id: params[:user_id])
@user.delete_all_posts!(guardian) @user.delete_all_posts!(guardian)
render nothing: true render nothing: true
end end
@ -157,7 +157,7 @@ class Admin::UsersController < Admin::AdminController
end end
def destroy def destroy
user = User.where(id: params[:id]).first user = User.find_by(id: params[:id])
guardian.ensure_can_delete_user!(user) guardian.ensure_can_delete_user!(user)
begin begin
if UserDestroyer.new(current_user).destroy(user, params.slice(:delete_posts, :block_email, :block_urls, :block_ip, :context)) if UserDestroyer.new(current_user).destroy(user, params.slice(:delete_posts, :block_email, :block_urls, :block_ip, :context))
@ -180,7 +180,7 @@ class Admin::UsersController < Admin::AdminController
private private
def fetch_user def fetch_user
@user = User.where(id: params[:user_id]).first @user = User.find_by(id: params[:user_id])
end end
def refresh_browser(user) def refresh_browser(user)

View File

@ -203,7 +203,7 @@ class ApplicationController < ActionController::Base
username_lower = params[:username].downcase username_lower = params[:username].downcase
username_lower.gsub!(/\.json$/, '') username_lower.gsub!(/\.json$/, '')
user = User.where(username_lower: username_lower).first user = User.find_by(username_lower: username_lower)
raise Discourse::NotFound.new if user.blank? raise Discourse::NotFound.new if user.blank?
guardian.ensure_can_see!(user) guardian.ensure_can_see!(user)

View File

@ -102,6 +102,6 @@ class CategoriesController < ApplicationController
end end
def fetch_category def fetch_category
@category = Category.where(slug: params[:id]).first || Category.where(id: params[:id].to_i).first @category = Category.find_by(slug: params[:id]) || Category.find_by(id: params[:id].to_i)
end end
end end

View File

@ -25,7 +25,7 @@ class GroupsController < ApplicationController
def find_group(param_name) def find_group(param_name)
name = params.require(param_name) name = params.require(param_name)
group = Group.where("lower(name) = ?", name.downcase).first group = Group.find_by("lower(name) = ?", name.downcase)
guardian.ensure_can_see!(group) guardian.ensure_can_see!(group)
group group
end end

View File

@ -6,7 +6,7 @@ class InvitesController < ApplicationController
before_filter :ensure_logged_in, only: [:destroy, :create] before_filter :ensure_logged_in, only: [:destroy, :create]
def show def show
invite = Invite.where(invite_key: params[:id]).first invite = Invite.find_by(invite_key: params[:id])
if invite.present? if invite.present?
user = invite.redeem user = invite.redeem
@ -42,7 +42,7 @@ class InvitesController < ApplicationController
def destroy def destroy
params.require(:email) params.require(:email)
invite = Invite.where(invited_by_id: current_user.id, email: params[:email]).first invite = Invite.find_by(invited_by_id: current_user.id, email: params[:email])
raise Discourse::InvalidParameters.new(:email) if invite.blank? raise Discourse::InvalidParameters.new(:email) if invite.blank?
invite.trash!(current_user) invite.trash!(current_user)

View File

@ -35,7 +35,7 @@ class PostActionsController < ApplicationController
end end
def destroy def destroy
post_action = current_user.post_actions.where(post_id: params[:id].to_i, post_action_type_id: @post_action_type_id, deleted_at: nil).first post_action = current_user.post_actions.find_by(post_id: params[:id].to_i, post_action_type_id: @post_action_type_id, deleted_at: nil)
raise Discourse::NotFound if post_action.blank? raise Discourse::NotFound if post_action.blank?

View File

@ -11,7 +11,7 @@ class PostsController < ApplicationController
skip_before_filter :check_xhr, only: [:markdown,:short_link] skip_before_filter :check_xhr, only: [:markdown,:short_link]
def markdown def markdown
post = Post.where(topic_id: params[:topic_id].to_i, post_number: (params[:post_number] || 1).to_i).first post = Post.find_by(topic_id: params[:topic_id].to_i, post_number: (params[:post_number] || 1).to_i)
if post && guardian.can_see?(post) if post && guardian.can_see?(post)
render text: post.raw, content_type: 'text/plain' render text: post.raw, content_type: 'text/plain'
else else
@ -208,7 +208,7 @@ class PostsController < ApplicationController
revision = params[:revision].to_i revision = params[:revision].to_i
raise Discourse::InvalidParameters.new(:revision) if revision < 2 raise Discourse::InvalidParameters.new(:revision) if revision < 2
post_revision = PostRevision.where(post_id: post_id, number: revision).first post_revision = PostRevision.find_by(post_id: post_id, number: revision)
post_revision.post = find_post_from_params post_revision.post = find_post_from_params
guardian.ensure_can_see!(post_revision) guardian.ensure_can_see!(post_revision)

View File

@ -25,9 +25,9 @@ class SearchController < ApplicationController
# A user is found by username # A user is found by username
context_obj = nil context_obj = nil
if search_context[:type] == 'user' if search_context[:type] == 'user'
context_obj = klass.where(username_lower: params[:search_context][:id].downcase).first context_obj = klass.find_by(username_lower: params[:search_context][:id].downcase)
else else
context_obj = klass.where(id: params[:search_context][:id]).first context_obj = klass.find_by(id: params[:search_context][:id])
end end
guardian.ensure_can_see!(context_obj) guardian.ensure_can_see!(context_obj)

View File

@ -43,7 +43,7 @@ class TopicsController < ApplicationController
begin begin
@topic_view = TopicView.new(params[:id] || params[:topic_id], current_user, opts) @topic_view = TopicView.new(params[:id] || params[:topic_id], current_user, opts)
rescue Discourse::NotFound rescue Discourse::NotFound
topic = Topic.where(slug: params[:id]).first if params[:id] topic = Topic.find_by(slug: params[:id]) if params[:id]
raise Discourse::NotFound unless topic raise Discourse::NotFound unless topic
return redirect_to(topic.relative_url) return redirect_to(topic.relative_url)
end end
@ -96,7 +96,7 @@ class TopicsController < ApplicationController
end end
def update def update
topic = Topic.where(id: params[:topic_id]).first topic = Topic.find_by(id: params[:topic_id])
title, archetype = params[:title], params[:archetype] title, archetype = params[:title], params[:archetype]
guardian.ensure_can_edit!(topic) guardian.ensure_can_edit!(topic)
@ -134,14 +134,14 @@ class TopicsController < ApplicationController
enabled = (params[:enabled] == 'true') enabled = (params[:enabled] == 'true')
check_for_status_presence(:status, status) check_for_status_presence(:status, status)
@topic = Topic.where(id: topic_id).first @topic = Topic.find_by(id: topic_id)
guardian.ensure_can_moderate!(@topic) guardian.ensure_can_moderate!(@topic)
@topic.update_status(status, enabled, current_user) @topic.update_status(status, enabled, current_user)
render nothing: true render nothing: true
end end
def star def star
@topic = Topic.where(id: params[:topic_id].to_i).first @topic = Topic.find_by(id: params[:topic_id].to_i)
guardian.ensure_can_see!(@topic) guardian.ensure_can_see!(@topic)
@topic.toggle_star(current_user, params[:starred] == 'true') @topic.toggle_star(current_user, params[:starred] == 'true')
@ -158,7 +158,7 @@ class TopicsController < ApplicationController
def autoclose def autoclose
raise Discourse::InvalidParameters.new(:auto_close_time) unless params.has_key?(:auto_close_time) raise Discourse::InvalidParameters.new(:auto_close_time) unless params.has_key?(:auto_close_time)
topic = Topic.where(id: params[:topic_id].to_i).first topic = Topic.find_by(id: params[:topic_id].to_i)
guardian.ensure_can_moderate!(topic) guardian.ensure_can_moderate!(topic)
topic.set_auto_close(params[:auto_close_time], current_user) topic.set_auto_close(params[:auto_close_time], current_user)
if topic.save if topic.save
@ -169,7 +169,7 @@ class TopicsController < ApplicationController
end end
def destroy def destroy
topic = Topic.where(id: params[:id]).first topic = Topic.find_by(id: params[:id])
guardian.ensure_can_delete!(topic) guardian.ensure_can_delete!(topic)
topic.trash!(current_user) topic.trash!(current_user)
render nothing: true render nothing: true
@ -188,7 +188,7 @@ class TopicsController < ApplicationController
def remove_allowed_user def remove_allowed_user
params.require(:username) params.require(:username)
topic = Topic.where(id: params[:topic_id]).first topic = Topic.find_by(id: params[:topic_id])
guardian.ensure_can_remove_allowed_users!(topic) guardian.ensure_can_remove_allowed_users!(topic)
if topic.remove_allowed_user(params[:username]) if topic.remove_allowed_user(params[:username])
@ -201,7 +201,7 @@ class TopicsController < ApplicationController
def invite def invite
username_or_email = params[:user] ? fetch_username : fetch_email username_or_email = params[:user] ? fetch_username : fetch_email
topic = Topic.where(id: params[:topic_id]).first topic = Topic.find_by(id: params[:topic_id])
guardian.ensure_can_invite_to!(topic) guardian.ensure_can_invite_to!(topic)
if topic.invite(current_user, username_or_email) if topic.invite(current_user, username_or_email)
@ -225,7 +225,7 @@ class TopicsController < ApplicationController
def merge_topic def merge_topic
params.require(:destination_topic_id) params.require(:destination_topic_id)
topic = Topic.where(id: params[:topic_id]).first topic = Topic.find_by(id: params[:topic_id])
guardian.ensure_can_move_posts!(topic) guardian.ensure_can_move_posts!(topic)
dest_topic = topic.move_posts(current_user, topic.posts.pluck(:id), destination_topic_id: params[:destination_topic_id].to_i) dest_topic = topic.move_posts(current_user, topic.posts.pluck(:id), destination_topic_id: params[:destination_topic_id].to_i)
@ -237,7 +237,7 @@ class TopicsController < ApplicationController
params.require(:topic_id) params.require(:topic_id)
params.permit(:category_id) params.permit(:category_id)
topic = Topic.where(id: params[:topic_id]).first topic = Topic.find_by(id: params[:topic_id])
guardian.ensure_can_move_posts!(topic) guardian.ensure_can_move_posts!(topic)
dest_topic = move_posts_to_destination(topic) dest_topic = move_posts_to_destination(topic)
@ -276,14 +276,14 @@ class TopicsController < ApplicationController
end end
def clear_pin def clear_pin
topic = Topic.where(id: params[:topic_id].to_i).first topic = Topic.find_by(id: params[:topic_id].to_i)
guardian.ensure_can_see!(topic) guardian.ensure_can_see!(topic)
topic.clear_pin_for(current_user) topic.clear_pin_for(current_user)
render nothing: true render nothing: true
end end
def re_pin def re_pin
topic = Topic.where(id: params[:topic_id].to_i).first topic = Topic.find_by(id: params[:topic_id].to_i)
guardian.ensure_can_see!(topic) guardian.ensure_can_see!(topic)
topic.re_pin_for(current_user) topic.re_pin_for(current_user)
render nothing: true render nothing: true
@ -330,7 +330,7 @@ class TopicsController < ApplicationController
private private
def toggle_mute def toggle_mute
@topic = Topic.where(id: params[:topic_id].to_i).first @topic = Topic.find_by(id: params[:topic_id].to_i)
guardian.ensure_can_see!(@topic) guardian.ensure_can_see!(@topic)
@topic.toggle_mute(current_user) @topic.toggle_mute(current_user)

View File

@ -23,7 +23,7 @@ class UploadsController < ApplicationController
url = request.fullpath url = request.fullpath
# the "url" parameter is here to prevent people from scanning the uploads using the id # the "url" parameter is here to prevent people from scanning the uploads using the id
if upload = Upload.where(id: id, url: url).first if upload = Upload.find_by(id: id, url: url)
send_file(Discourse.store.path_for(upload), filename: upload.original_filename) send_file(Discourse.store.path_for(upload), filename: upload.original_filename)
else else
render nothing: true, status: 404 render nothing: true, status: 404

View File

@ -56,9 +56,9 @@ class UserBadgesController < ApplicationController
params.permit(:badge_name) params.permit(:badge_name)
if params[:badge_name].nil? if params[:badge_name].nil?
params.require(:badge_id) params.require(:badge_id)
badge = Badge.where(id: params[:badge_id]).first badge = Badge.find_by(id: params[:badge_id])
else else
badge = Badge.where(name: params[:badge_name]).first badge = Badge.find_by(name: params[:badge_name])
end end
raise Discourse::NotFound.new if badge.blank? raise Discourse::NotFound.new if badge.blank?

View File

@ -312,7 +312,7 @@ class UsersController < ApplicationController
# [LEGACY] avatars in quotes/oneboxes might still be pointing to this route # [LEGACY] avatars in quotes/oneboxes might still be pointing to this route
# fixing it requires a rebake of all the posts # fixing it requires a rebake of all the posts
def avatar def avatar
user = User.where(username_lower: params[:username].downcase).first user = User.find_by(username_lower: params[:username].downcase)
if user.present? if user.present?
size = determine_avatar_size(params[:size]) size = determine_avatar_size(params[:size])
url = user.avatar_template.gsub("{size}", size.to_s) url = user.avatar_template.gsub("{size}", size.to_s)

View File

@ -2,8 +2,8 @@ module Jobs
class CloseTopic < Jobs::Base class CloseTopic < Jobs::Base
def execute(args) def execute(args)
if topic = Topic.where(id: args[:topic_id]).first if topic = Topic.find_by(id: args[:topic_id])
closer = User.where(id: args[:user_id]).first closer = User.find_by(id: args[:user_id])
topic.auto_close(closer) topic.auto_close(closer)
end end
end end

View File

@ -83,7 +83,7 @@ module Jobs
def execute(args) def execute(args)
raise Discourse::InvalidParameters.new(:topic_link_id) unless args[:topic_link_id].present? raise Discourse::InvalidParameters.new(:topic_link_id) unless args[:topic_link_id].present?
topic_link = TopicLink.where(id: args[:topic_link_id], internal: false, crawled_at: nil).first topic_link = TopicLink.find_by(id: args[:topic_link_id], internal: false, crawled_at: nil)
return if topic_link.blank? return if topic_link.blank?
# Look for a topic embed for the URL. If it exists, use its title and don't crawl # Look for a topic embed for the URL. If it exists, use its title and don't crawl

View File

@ -6,7 +6,7 @@ module Jobs
topic_id = args[:topic_id] topic_id = args[:topic_id]
raise Discourse::InvalidParameters.new(:topic_id) unless topic_id.present? raise Discourse::InvalidParameters.new(:topic_id) unless topic_id.present?
topic = Topic.where(id: topic_id).first topic = Topic.find_by(id: topic_id)
# there are 3 cases here # there are 3 cases here
# 1. topic was atomically nuked, this should be skipped # 1. topic was atomically nuked, this should be skipped

View File

@ -11,8 +11,8 @@ module Jobs
raise Discourse::InvalidParameters.new(:upload_id) if upload_id.blank? raise Discourse::InvalidParameters.new(:upload_id) if upload_id.blank?
raise Discourse::InvalidParameters.new(:user_id) if user_id.blank? raise Discourse::InvalidParameters.new(:user_id) if user_id.blank?
upload = Upload.where(id: upload_id).first upload = Upload.find_by(id: upload_id)
user = User.where(id: user_id).first user = User.find_by(id: user_id)
return if upload.nil? || user.nil? return if upload.nil? || user.nil?
external_copy = Discourse.store.download(upload) if Discourse.store.external? external_copy = Discourse.store.download(upload) if Discourse.store.external?

View File

@ -8,7 +8,7 @@ module Jobs
def execute(args) def execute(args)
raise Discourse::InvalidParameters.new(:invite_id) unless args[:invite_id].present? raise Discourse::InvalidParameters.new(:invite_id) unless args[:invite_id].present?
invite = Invite.where(id: args[:invite_id]).first invite = Invite.find_by(id: args[:invite_id])
message = InviteMailer.send_invite(invite) message = InviteMailer.send_invite(invite)
Email::Sender.new(message, :invite).send Email::Sender.new(message, :invite).send
end end

View File

@ -5,7 +5,7 @@ module Jobs
def execute(args) def execute(args)
post_id = args[:post_id] post_id = args[:post_id]
if post_id if post_id
post = Post.with_deleted.where(id: post_id).first post = Post.with_deleted.find_by(id: post_id)
return if post && post.trashed? return if post && post.trashed?
end end

View File

@ -10,7 +10,7 @@ module Jobs
users_notified = Set.new users_notified = Set.new
posts = Post.where(id: args[:post_ids]).where('user_id <> ?', args[:moved_by_id]).includes(:user, :topic) posts = Post.where(id: args[:post_ids]).where('user_id <> ?', args[:moved_by_id]).includes(:user, :topic)
if posts.present? if posts.present?
moved_by = User.where(id: args[:moved_by_id]).first moved_by = User.find_by(id: args[:moved_by_id])
posts.each do |p| posts.each do |p|
unless users_notified.include?(p.user_id) unless users_notified.include?(p.user_id)

View File

@ -6,7 +6,7 @@ module Jobs
class ProcessPost < Jobs::Base class ProcessPost < Jobs::Base
def execute(args) def execute(args)
post = Post.where(id: args[:post_id]).first post = Post.find_by(id: args[:post_id])
# two levels of deletion # two levels of deletion
return unless post.present? && post.topic.present? return unless post.present? && post.topic.present?

View File

@ -17,7 +17,7 @@ module Jobs
post_id = args[:post_id] post_id = args[:post_id]
raise Discourse::InvalidParameters.new(:post_id) unless post_id.present? raise Discourse::InvalidParameters.new(:post_id) unless post_id.present?
post = Post.where(id: post_id).first post = Post.find_by(id: post_id)
return unless post.present? return unless post.present?
raw = post.raw.dup raw = post.raw.dup

View File

@ -11,7 +11,7 @@ module Jobs
user = nil user = nil
if args[:user_id] if args[:user_id]
user = User.where(id: args[:user_id]).first user = User.find_by(id: args[:user_id])
end end
TopicRetriever.new(args[:embed_url], no_throttle: user.try(:staff?)).retrieve TopicRetriever.new(args[:embed_url], no_throttle: user.try(:staff?)).retrieve

View File

@ -9,7 +9,7 @@ module Jobs
raise Discourse::InvalidParameters.new(:user_id) unless args[:user_id].present? raise Discourse::InvalidParameters.new(:user_id) unless args[:user_id].present?
raise Discourse::InvalidParameters.new(:message_type) unless args[:message_type].present? raise Discourse::InvalidParameters.new(:message_type) unless args[:message_type].present?
user = User.where(id: args[:user_id]).first user = User.find_by(id: args[:user_id])
return if user.blank? return if user.blank?
system_message = SystemMessage.new(user) system_message = SystemMessage.new(user)

View File

@ -3,7 +3,7 @@ module Jobs
class UpdateTopRedirection < Jobs::Base class UpdateTopRedirection < Jobs::Base
def execute(args) def execute(args)
user = User.where(id: args[:user_id]).first user = User.find_by(id: args[:user_id])
user.update_column(:last_redirected_to_top_at, args[:redirected_at]) user.update_column(:last_redirected_to_top_at, args[:redirected_at])
end end
end end

View File

@ -14,7 +14,7 @@ module Jobs
raise Discourse::InvalidParameters.new(:type) unless args[:type].present? raise Discourse::InvalidParameters.new(:type) unless args[:type].present?
# Find the user # Find the user
@user = User.where(id: args[:user_id]).first @user = User.find_by(id: args[:user_id])
return skip(I18n.t("email_log.no_user", user_id: args[:user_id])) unless @user return skip(I18n.t("email_log.no_user", user_id: args[:user_id])) unless @user
return skip(I18n.t("email_log.suspended_not_pm")) if @user.suspended? && args[:type] != :user_private_message return skip(I18n.t("email_log.suspended_not_pm")) if @user.suspended? && args[:type] != :user_private_message
@ -27,7 +27,7 @@ module Jobs
# Don't email a user about a post when we've seen them recently. # Don't email a user about a post when we've seen them recently.
return skip(I18n.t('email_log.seen_recently')) if seen_recently return skip(I18n.t('email_log.seen_recently')) if seen_recently
post = Post.where(id: args[:post_id]).first post = Post.find_by(id: args[:post_id])
return skip(I18n.t('email_log.post_not_found', post_id: args[:post_id])) unless post.present? return skip(I18n.t('email_log.post_not_found', post_id: args[:post_id])) unless post.present?
email_args[:post] = post email_args[:post] = post
@ -36,13 +36,13 @@ module Jobs
email_args[:email_token] = args[:email_token] if args[:email_token].present? email_args[:email_token] = args[:email_token] if args[:email_token].present?
notification = nil notification = nil
notification = Notification.where(id: args[:notification_id]).first if args[:notification_id].present? notification = Notification.find_by(id: args[:notification_id]) if args[:notification_id].present?
if notification.present? if notification.present?
# Don't email a user about a post when we've seen them recently. # Don't email a user about a post when we've seen them recently.
return skip(I18n.t('email_log.seen_recently')) if seen_recently && !@user.suspended? return skip(I18n.t('email_log.seen_recently')) if seen_recently && !@user.suspended?
# Load the post if present # Load the post if present
email_args[:post] ||= Post.where(id: notification.data_hash[:original_post_id].to_i).first email_args[:post] ||= Post.find_by(id: notification.data_hash[:original_post_id].to_i)
email_args[:post] ||= notification.post email_args[:post] ||= notification.post
email_args[:notification] = notification email_args[:notification] = notification

View File

@ -23,7 +23,7 @@ module Jobs
end end
def poll_feed def poll_feed
user = User.where(username_lower: SiteSetting.embed_by_username.downcase).first user = User.find_by(username_lower: SiteSetting.embed_by_username.downcase)
return if user.blank? return if user.blank?
require 'simple-rss' require 'simple-rss'

View File

@ -12,7 +12,7 @@ class ApiKey < ActiveRecord::Base
end end
def self.create_master_key def self.create_master_key
api_key = ApiKey.where(user_id: nil).first api_key = ApiKey.find_by(user_id: nil)
if api_key.blank? if api_key.blank?
api_key = ApiKey.create(key: SecureRandom.hex(32), created_by: Discourse.system_user) api_key = ApiKey.create(key: SecureRandom.hex(32), created_by: Discourse.system_user)
end end

View File

@ -306,7 +306,7 @@ SQL
end end
def self.find_by_email(email) def self.find_by_email(email)
self.where(email_in: Email.downcase(email)).first self.find_by(email_in: Email.downcase(email))
end end
def has_children? def has_children?

View File

@ -9,7 +9,7 @@ class ColorScheme < ActiveRecord::Base
after_destroy :destroy_versions after_destroy :destroy_versions
def self.enabled def self.enabled
current_version.where(enabled: true).first || find(1) current_version.find_by(enabled: true) || find(1)
end end
def can_edit? def can_edit?

View File

@ -41,7 +41,7 @@ class DiscourseSingleSignOn < SingleSignOn
end end
def lookup_or_create_user def lookup_or_create_user
sso_record = SingleSignOnRecord.where(external_id: external_id).first sso_record = SingleSignOnRecord.find_by(external_id: external_id)
if sso_record && user = sso_record.user if sso_record && user = sso_record.user
sso_record.last_payload = unsigned_payload sso_record.last_payload = unsigned_payload
@ -75,7 +75,7 @@ class DiscourseSingleSignOn < SingleSignOn
private private
def match_email_or_create_user def match_email_or_create_user
user = User.where(email: Email.downcase(email)).first user = User.find_by(email: Email.downcase(email))
user_params = { user_params = {
email: email, email: email,

View File

@ -3,7 +3,7 @@ class DraftSequence < ActiveRecord::Base
user_id = user user_id = user
user_id = user.id unless user.class == Fixnum user_id = user.id unless user.class == Fixnum
h = { user_id: user_id, draft_key: key } h = { user_id: user_id, draft_key: key }
c = DraftSequence.where(h).first c = DraftSequence.find_by(h)
c ||= DraftSequence.new(h) c ||= DraftSequence.new(h)
c.sequence ||= 0 c.sequence ||= 0
c.sequence += 1 c.sequence += 1

View File

@ -19,7 +19,7 @@ class EmailLog < ActiveRecord::Base
end end
def self.for(reply_key) def self.for(reply_key)
EmailLog.where(reply_key: reply_key).first EmailLog.find_by(reply_key: reply_key)
end end
def self.last_sent_email_address def self.last_sent_email_address

View File

@ -155,9 +155,9 @@ class Group < ActiveRecord::Base
def self.lookup_group(name) def self.lookup_group(name)
if id = AUTO_GROUPS[name] if id = AUTO_GROUPS[name]
Group.where(id: id).first Group.find_by(id: id)
else else
unless group = Group.where(name: name).first unless group = Group.find_by(name: name)
raise ArgumentError, "unknown group" raise ArgumentError, "unknown group"
end end
group group

View File

@ -13,7 +13,7 @@ class IncomingLink < ActiveRecord::Base
user_id, host, referer = nil user_id, host, referer = nil
if request['u'] if request['u']
u = User.select(:id).where(username_lower: request['u'].downcase).first u = User.select(:id).find_by(username_lower: request["u"].downcase)
user_id = u.id if u user_id = u.id if u
end end

View File

@ -24,7 +24,7 @@ class Invite < ActiveRecord::Base
def user_doesnt_already_exist def user_doesnt_already_exist
@email_already_exists = false @email_already_exists = false
return if email.blank? return if email.blank?
u = User.where("email = ?", Email.downcase(email)).first u = User.find_by("email = ?", Email.downcase(email))
if u && u.id != self.user_id if u && u.id != self.user_id
@email_already_exists = true @email_already_exists = true
errors.add(:email) errors.add(:email)
@ -106,7 +106,7 @@ class Invite < ActiveRecord::Base
end end
def self.invalidate_for_email(email) def self.invalidate_for_email(email)
i = Invite.where(email: Email.downcase(email)).first i = Invite.find_by(email: Email.downcase(email))
if i if i
i.invalidated_at = Time.zone.now i.invalidated_at = Time.zone.now
i.save i.save

View File

@ -57,7 +57,7 @@ InviteRedeemer = Struct.new(:invite) do
end end
def get_existing_user def get_existing_user
User.where(email: invite.email).first User.find_by(email: invite.email)
end end

View File

@ -87,7 +87,7 @@ class Notification < ActiveRecord::Base
def post def post
return if topic_id.blank? || post_number.blank? return if topic_id.blank? || post_number.blank?
Post.where(topic_id: topic_id, post_number: post_number).first Post.find_by(topic_id: topic_id, post_number: post_number)
end end
def self.recent_report(user, count = nil) def self.recent_report(user, count = nil)

View File

@ -7,7 +7,7 @@ class OptimizedImage < ActiveRecord::Base
return unless width > 0 && height > 0 return unless width > 0 && height > 0
# do we already have that thumbnail? # do we already have that thumbnail?
thumbnail = where(upload_id: upload.id, width: width, height: height).first thumbnail = find_by(upload_id: upload.id, width: width, height: height)
# make sure the previous thumbnail has not failed # make sure the previous thumbnail has not failed
if thumbnail && thumbnail.url.blank? if thumbnail && thumbnail.url.blank?

View File

@ -1,14 +1,14 @@
# API to wrap up plugin store rows # API to wrap up plugin store rows
class PluginStore class PluginStore
def self.get(plugin_name, key) def self.get(plugin_name, key)
if row = PluginStoreRow.where(plugin_name: plugin_name, key: key).first if row = PluginStoreRow.find_by(plugin_name: plugin_name, key: key)
cast_value(row.type_name, row.value) cast_value(row.type_name, row.value)
end end
end end
def self.set(plugin_name, key, value) def self.set(plugin_name, key, value)
hash = {plugin_name: plugin_name, key: key} hash = {plugin_name: plugin_name, key: key}
row = PluginStoreRow.where(hash).first || row = PluginStoreRow.new(hash) row = PluginStoreRow.find_by(hash) || row = PluginStoreRow.new(hash)
row.type_name = determine_type(value) row.type_name = determine_type(value)
# nil are stored as nil # nil are stored as nil

View File

@ -67,7 +67,7 @@ class Post < ActiveRecord::Base
end end
def self.find_by_detail(key, value) def self.find_by_detail(key, value)
includes(:post_details).where(post_details: { key: key, value: value }).first includes(:post_details).find_by(post_details: { key: key, value: value })
end end
def add_detail(key, value, extra = nil) def add_detail(key, value, extra = nil)
@ -250,17 +250,12 @@ class Post < ActiveRecord::Base
def reply_to_post def reply_to_post
return if reply_to_post_number.blank? return if reply_to_post_number.blank?
@reply_to_post ||= Post.where("topic_id = :topic_id AND post_number = :post_number", @reply_to_post ||= Post.find_by("topic_id = :topic_id AND post_number = :post_number", topic_id: topic_id, post_number: reply_to_post_number)
topic_id: topic_id,
post_number: reply_to_post_number).first
end end
def reply_notification_target def reply_notification_target
return if reply_to_post_number.blank? return if reply_to_post_number.blank?
Post.where("topic_id = :topic_id AND post_number = :post_number AND user_id <> :user_id", Post.find_by("topic_id = :topic_id AND post_number = :post_number AND user_id <> :user_id", topic_id: topic_id, post_number: reply_to_post_number, user_id: user_id).try(:user)
topic_id: topic_id,
post_number: reply_to_post_number,
user_id: user_id).first.try(:user)
end end
def self.excerpt(cooked, maxlength = nil, options = {}) def self.excerpt(cooked, maxlength = nil, options = {})
@ -401,7 +396,7 @@ class Post < ActiveRecord::Base
# Create a reply relationship between quoted posts and this new post # Create a reply relationship between quoted posts and this new post
self.quoted_post_numbers.each do |p| self.quoted_post_numbers.each do |p|
post = Post.where(topic_id: topic_id, post_number: p).first post = Post.find_by(topic_id: topic_id, post_number: p)
create_reply_relationship_with(post) create_reply_relationship_with(post)
end end
end end
@ -442,7 +437,7 @@ class Post < ActiveRecord::Base
def revert_to(number) def revert_to(number)
return if number >= version return if number >= version
post_revision = PostRevision.where(post_id: id, number: number + 1).first post_revision = PostRevision.find_by(post_id: id, number: (number + 1))
post_revision.modifications.each do |attribute, change| post_revision.modifications.each do |attribute, change|
attribute = "version" if attribute == "cached_version" attribute = "version" if attribute == "cached_version"
write_attribute(attribute, change[0]) write_attribute(attribute, change[0])
@ -495,7 +490,7 @@ class Post < ActiveRecord::Base
end end
def update_revision def update_revision
revision = PostRevision.where(post_id: id, number: version).first revision = PostRevision.find_by(post_id: id, number: version)
return unless revision return unless revision
revision.user_id = last_editor_id revision.user_id = last_editor_id
modifications = changes.extract!(:raw, :cooked, :edit_reason) modifications = changes.extract!(:raw, :cooked, :edit_reason)

View File

@ -143,9 +143,7 @@ class PostAction < ActiveRecord::Base
end end
def self.remove_act(user, post, post_action_type_id) def self.remove_act(user, post, post_action_type_id)
if action = where(post_id: post.id, if action = find_by(post_id: post.id, user_id: user.id, post_action_type_id: post_action_type_id)
user_id: user.id,
post_action_type_id: post_action_type_id).first
action.remove_act!(user) action.remove_act!(user)
end end
end end
@ -319,7 +317,7 @@ class PostAction < ActiveRecord::Base
end end
def self.post_action_type_for_post(post_id) def self.post_action_type_for_post(post_id)
post_action = PostAction.where(defer: nil, post_id: post_id, post_action_type_id: PostActionType.flag_types.values, deleted_at: nil).first post_action = PostAction.find_by(defer: nil, post_id: post_id, post_action_type_id: PostActionType.flag_types.values, deleted_at: nil)
PostActionType.types[post_action.post_action_type_id] PostActionType.types[post_action.post_action_type_id]
end end

View File

@ -47,8 +47,8 @@ class PostRevision < ActiveRecord::Base
return if prev == cur return if prev == cur
{ {
previous_user: User.where(id: prev).first, previous_user: User.find_by(id: prev),
current_user: User.where(id: cur).first current_user: User.find_by(id: cur)
} }
end end

View File

@ -17,7 +17,7 @@ class ScreenedEmail < ActiveRecord::Base
end end
def self.should_block?(email) def self.should_block?(email)
screened_email = ScreenedEmail.where(email: email).first screened_email = ScreenedEmail.find_by(email: email)
screened_email.record_match! if screened_email screened_email.record_match! if screened_email
screened_email && screened_email.action_type == actions[:block] screened_email && screened_email.action_type == actions[:block]
end end

View File

@ -65,7 +65,7 @@ class ScreenedIpAddress < ActiveRecord::Base
# #
# http://www.postgresql.org/docs/9.1/static/datatype-net-types.html # http://www.postgresql.org/docs/9.1/static/datatype-net-types.html
# http://www.postgresql.org/docs/9.1/static/functions-net.html # http://www.postgresql.org/docs/9.1/static/functions-net.html
where("'#{ip_address.to_s}' <<= ip_address").first find_by("'#{ip_address.to_s}' <<= ip_address")
end end
def self.should_block?(ip_address) def self.should_block?(ip_address)

View File

@ -50,7 +50,7 @@ class SearchObserver < ActiveRecord::Observer
if obj.class == Topic && obj.title_changed? if obj.class == Topic && obj.title_changed?
if obj.posts if obj.posts
post = obj.posts.where(post_number: 1).first post = obj.posts.find_by(post_number: 1)
if post if post
category_name = obj.category.name if obj.category category_name = obj.category.name if obj.category
SearchObserver.update_posts_index(post.id, post.cooked, obj.title, category_name) SearchObserver.update_posts_index(post.id, post.cooked, obj.title, category_name)

View File

@ -99,7 +99,7 @@ class SiteCustomization < ActiveRecord::Base
return preview_style if preview_style return preview_style if preview_style
@lock.synchronize do @lock.synchronize do
style = where(enabled: true).first style = find_by(enabled: true)
if style if style
@cache[enabled_key] = style.key @cache[enabled_key] = style.key
else else
@ -141,7 +141,7 @@ class SiteCustomization < ActiveRecord::Base
return style if style return style if style
@lock.synchronize do @lock.synchronize do
style = where(key: key).first style = find_by(key: key)
style.ensure_stylesheets_on_disk! if style style.ensure_stylesheets_on_disk! if style
@cache[key] = style @cache[key] = style
end end

View File

@ -447,7 +447,7 @@ class Topic < ActiveRecord::Base
end end
def changed_to_category(cat) def changed_to_category(cat)
return true if cat.blank? || Category.where(topic_id: id).first.present? return true if cat.blank? || Category.find_by(topic_id: id).present?
Topic.transaction do Topic.transaction do
old_category = category old_category = category
@ -502,9 +502,9 @@ class Topic < ActiveRecord::Base
def change_category(name) def change_category(name)
# If the category name is blank, reset the attribute # If the category name is blank, reset the attribute
if name.blank? if name.blank?
cat = Category.where(id: SiteSetting.uncategorized_category_id).first cat = Category.find_by(id: SiteSetting.uncategorized_category_id)
else else
cat = Category.where(name: name).first cat = Category.find_by(name: name)
end end
return true if cat == category return true if cat == category
@ -514,9 +514,9 @@ class Topic < ActiveRecord::Base
def remove_allowed_user(username) def remove_allowed_user(username)
user = User.where(username: username).first user = User.find_by(username: username)
if user if user
topic_user = topic_allowed_users.where(user_id: user.id).first topic_user = topic_allowed_users.find_by(user_id: user.id)
if topic_user if topic_user
topic_user.destroy topic_user.destroy
else else
@ -559,7 +559,7 @@ class Topic < ActiveRecord::Base
end end
def grant_permission_to_user(lower_email) def grant_permission_to_user(lower_email)
user = User.where(email: lower_email).first user = User.find_by(email: lower_email)
topic_allowed_users.create!(user_id: user.id) topic_allowed_users.create!(user_id: user.id)
end end

View File

@ -24,7 +24,7 @@ class TopicEmbed < ActiveRecord::Base
url = normalize_url(url) url = normalize_url(url)
embed = TopicEmbed.where("lower(embed_url) = ?", url).first embed = TopicEmbed.find_by("lower(embed_url) = ?", url)
content_sha1 = Digest::SHA1.hexdigest(contents) content_sha1 = Digest::SHA1.hexdigest(contents)
post = nil post = nil

View File

@ -123,7 +123,7 @@ class TopicLink < ActiveRecord::Base
post_number = route[:post_number] || 1 post_number = route[:post_number] || 1
# Store the canonical URL # Store the canonical URL
topic = Topic.where(id: topic_id).first topic = Topic.find_by(id: topic_id)
if topic.present? if topic.present?
url = "#{Discourse.base_url}#{topic.relative_url}" url = "#{Discourse.base_url}#{topic.relative_url}"
@ -137,7 +137,7 @@ class TopicLink < ActiveRecord::Base
reflected_post = nil reflected_post = nil
if post_number && topic_id if post_number && topic_id
reflected_post = Post.where(topic_id: topic_id, post_number: post_number.to_i).first reflected_post = Post.find_by(topic_id: topic_id, post_number: post_number.to_i)
end end
added_urls << url added_urls << url
@ -152,7 +152,7 @@ class TopicLink < ActiveRecord::Base
# Create the reflection if we can # Create the reflection if we can
if topic_id.present? if topic_id.present?
topic = Topic.where(id: topic_id).first topic = Topic.find_by(id: topic_id)
if topic && post.topic && post.topic.archetype != 'private_message' && topic.archetype != 'private_message' if topic && post.topic && post.topic.archetype != 'private_message' && topic.archetype != 'private_message'

View File

@ -33,7 +33,7 @@ class TopicLinkClick < ActiveRecord::Base
# If we have it somewhere else on the site, just allow the redirect. This is # If we have it somewhere else on the site, just allow the redirect. This is
# likely due to a onebox of another topic. # likely due to a onebox of another topic.
link = TopicLink.where(url: args[:url]).first link = TopicLink.find_by(url: args[:url])
return link.present? ? link.url : nil return link.present? ? link.url : nil
end end

View File

@ -24,7 +24,7 @@ class TopicNotifier
end end
def muted?(user_id) def muted?(user_id)
tu = @topic.topic_users.where(user_id: user_id).first tu = @topic.topic_users.find_by(user_id: user_id)
tu && tu.notification_level == levels[:muted] tu && tu.notification_level == levels[:muted]
end end

View File

@ -99,7 +99,7 @@ class TopicUser < ActiveRecord::Base
if rows == 0 if rows == 0
now = DateTime.now now = DateTime.now
auto_track_after = User.select(:auto_track_topics_after_msecs).where(id: user_id).first.auto_track_topics_after_msecs auto_track_after = User.select(:auto_track_topics_after_msecs).find_by(id: user_id).auto_track_topics_after_msecs
auto_track_after ||= SiteSetting.auto_track_topics_after auto_track_after ||= SiteSetting.auto_track_topics_after
if auto_track_after >= 0 && auto_track_after <= (attrs[:total_msecs_viewed] || 0) if auto_track_after >= 0 && auto_track_after <= (attrs[:total_msecs_viewed] || 0)

View File

@ -17,7 +17,7 @@ class Upload < ActiveRecord::Base
validates_with ::Validators::UploadValidator validates_with ::Validators::UploadValidator
def thumbnail(width = self.width, height = self.height) def thumbnail(width = self.width, height = self.height)
optimized_images.where(width: width, height: height).first optimized_images.find_by(width: width, height: height)
end end
def has_thumbnail?(width, height) def has_thumbnail?(width, height)
@ -53,7 +53,7 @@ class Upload < ActiveRecord::Base
# compute the sha # compute the sha
sha1 = Digest::SHA1.file(file).hexdigest sha1 = Digest::SHA1.file(file).hexdigest
# check if the file has already been uploaded # check if the file has already been uploaded
upload = Upload.where(sha1: sha1).first upload = Upload.find_by(sha1: sha1)
# delete the previously uploaded file if there's been an error # delete the previously uploaded file if there's been an error
if upload && upload.url.blank? if upload && upload.url.blank?
upload.destroy upload.destroy
@ -112,7 +112,7 @@ class Upload < ActiveRecord::Base
def self.get_from_url(url) def self.get_from_url(url)
# we store relative urls, so we need to remove any host/cdn # we store relative urls, so we need to remove any host/cdn
url = url.gsub(/^#{Discourse.asset_host}/i, "") if Discourse.asset_host.present? url = url.gsub(/^#{Discourse.asset_host}/i, "") if Discourse.asset_host.present?
Upload.where(url: url).first if Discourse.store.has_been_uploaded?(url) Upload.find_by(url: url) if Discourse.store.has_been_uploaded?(url)
end end
end end

View File

@ -138,7 +138,7 @@ class User < ActiveRecord::Base
def self.find_by_temporary_key(key) def self.find_by_temporary_key(key)
user_id = $redis.get("temporary_key:#{key}") user_id = $redis.get("temporary_key:#{key}")
if user_id.present? if user_id.present?
where(id: user_id.to_i).first find_by(id: user_id.to_i)
end end
end end
@ -151,11 +151,11 @@ class User < ActiveRecord::Base
end end
def self.find_by_email(email) def self.find_by_email(email)
where(email: Email.downcase(email)).first find_by(email: Email.downcase(email))
end end
def self.find_by_username(username) def self.find_by_username(username)
where(username_lower: username.downcase).first find_by(username_lower: username.downcase)
end end
@ -296,7 +296,7 @@ class User < ActiveRecord::Base
end end
def visit_record_for(date) def visit_record_for(date)
user_visits.where(visited_at: date).first user_visits.find_by(visited_at: date)
end end
def update_visit_record!(date) def update_visit_record!(date)
@ -676,7 +676,7 @@ class User < ActiveRecord::Base
def username_validator def username_validator
username_format_validator || begin username_format_validator || begin
lower = username.downcase lower = username.downcase
existing = User.where(username_lower: lower).first existing = User.find_by(username_lower: lower)
if username_changed? && existing && existing.id != self.id if username_changed? && existing && existing.id != self.id
errors.add(:username, I18n.t(:'user.username.unique')) errors.add(:username, I18n.t(:'user.username.unique'))
end end

View File

@ -155,7 +155,9 @@ LEFT JOIN categories c on c.id = t.category_id
# TODO there are conditions when this is called and user_id was already rolled back and is invalid. # TODO there are conditions when this is called and user_id was already rolled back and is invalid.
# protect against dupes, for some reason this is failing in some cases # protect against dupes, for some reason this is failing in some cases
action = self.where(hash.select{|k,v| required_parameters.include?(k)}).first action = self.find_by(hash.select do |k, v|
required_parameters.include?(k)
end)
return action if action return action if action
action = self.new(hash) action = self.new(hash)
@ -168,7 +170,7 @@ LEFT JOIN categories c on c.id = t.category_id
user_id = hash[:user_id] user_id = hash[:user_id]
update_like_count(user_id, hash[:action_type], 1) update_like_count(user_id, hash[:action_type], 1)
topic = Topic.includes(:category).where(id: hash[:target_topic_id]).first topic = Topic.includes(:category).find_by(id: hash[:target_topic_id])
# move into Topic perhaps # move into Topic perhaps
group_ids = nil group_ids = nil
@ -194,7 +196,7 @@ LEFT JOIN categories c on c.id = t.category_id
def self.remove_action!(hash) def self.remove_action!(hash)
require_parameters(hash, :action_type, :user_id, :acting_user_id, :target_topic_id, :target_post_id) require_parameters(hash, :action_type, :user_id, :acting_user_id, :target_topic_id, :target_post_id)
if action = UserAction.where(hash.except(:created_at)).first if action = UserAction.find_by(hash.except(:created_at))
action.destroy action.destroy
MessageBus.publish("/user/#{hash[:user_id]}", {user_action_id: action.id, remove: true}) MessageBus.publish("/user/#{hash[:user_id]}", {user_action_id: action.id, remove: true})
end end

View File

@ -137,7 +137,7 @@ class PostAlerter
# Returns a list of users who were quoted in the post # Returns a list of users who were quoted in the post
def extract_quoted_users(post) def extract_quoted_users(post)
post.raw.scan(/\[quote=\"([^,]+),.+\"\]/).uniq.map do |m| post.raw.scan(/\[quote=\"([^,]+),.+\"\]/).uniq.map do |m|
User.where("username_lower = :username and id != :id", username: m.first.strip.downcase, id: post.user_id).first User.find_by("username_lower = :username and id != :id", username: m.first.strip.downcase, id: post.user_id)
end.compact end.compact
end end

View File

@ -53,7 +53,7 @@ class UserDestroyer
categories.each do |c| categories.each do |c|
c.user_id = Discourse.system_user.id c.user_id = Discourse.system_user.id
c.save! c.save!
if topic = Topic.with_deleted.where(id: c.topic_id).first if topic = Topic.with_deleted.find_by(id: c.topic_id)
topic.try(:recover!) topic.try(:recover!)
topic.user_id = Discourse.system_user.id topic.user_id = Discourse.system_user.id
topic.save! topic.save!

View File

@ -1,7 +1,7 @@
# kind of odd, but we need it, we also need to nuke usage of User from inside migrations # kind of odd, but we need it, we also need to nuke usage of User from inside migrations
# very poor form # very poor form
User.reset_column_information User.reset_column_information
user = User.where("id <> -1 and username_lower = 'system'").first user = User.find_by("id <> -1 and username_lower = 'system'")
if user if user
user.username = UserNameSuggester.suggest("system") user.username = UserNameSuggester.suggest("system")
user.save user.save

View File

@ -1,5 +1,5 @@
unless Rails.env.test? unless Rails.env.test?
lounge = Category.where(id: SiteSetting.lounge_category_id).first lounge = Category.find_by(id: SiteSetting.lounge_category_id)
if lounge and !lounge.group_ids.include?(Group[:trust_level_3].id) if lounge and !lounge.group_ids.include?(Group[:trust_level_3].id)
# The category for users with trust level 3 has been created. # The category for users with trust level 3 has been created.

View File

@ -1,5 +1,5 @@
unless Rails.env.test? unless Rails.env.test?
meta = Category.where(id: SiteSetting.meta_category_id).first meta = Category.find_by(id: SiteSetting.meta_category_id)
if meta && !meta.topic_id if meta && !meta.topic_id
Category.transaction do Category.transaction do

View File

@ -1,5 +1,5 @@
unless Rails.env.test? unless Rails.env.test?
staff = Category.where(id: SiteSetting.staff_category_id).first staff = Category.find_by(id: SiteSetting.staff_category_id)
if staff and !staff.group_ids.include?(Group[:staff].id) if staff and !staff.group_ids.include?(Group[:staff].id)
# Add permissions and a description to the Staff category. # Add permissions and a description to the Staff category.

View File

@ -5,7 +5,7 @@ Post.reset_column_information
if Topic.where('id NOT IN (SELECT topic_id from categories where topic_id is not null)').count == 0 && !Rails.env.test? if Topic.where('id NOT IN (SELECT topic_id from categories where topic_id is not null)').count == 0 && !Rails.env.test?
puts "Seeding welcome topics" puts "Seeding welcome topics"
staff = Category.where(id: SiteSetting.staff_category_id).first staff = Category.find_by(id: SiteSetting.staff_category_id)
welcome = File.read(Rails.root + 'docs/ADMIN-QUICK-START-GUIDE.md') welcome = File.read(Rails.root + 'docs/ADMIN-QUICK-START-GUIDE.md')
PostCreator.create(Discourse.system_user, raw: welcome, title: "READ ME FIRST: Admin Quick Start Guide", skip_validations: true, category: staff ? staff.name : nil) PostCreator.create(Discourse.system_user, raw: welcome, title: "READ ME FIRST: Admin Quick Start Guide", skip_validations: true, category: staff ? staff.name : nil)
PostCreator.create(Discourse.system_user, raw: I18n.t('assets_topic_body'), title: "Assets for the forum design", skip_validations: true, category: staff ? staff.name : nil) PostCreator.create(Discourse.system_user, raw: I18n.t('assets_topic_body'), title: "Assets for the forum design", skip_validations: true, category: staff ? staff.name : nil)

View File

@ -8,7 +8,7 @@ class FixLinkPostId < ActiveRecord::Migration
parsed = URI.parse(tl.url) parsed = URI.parse(tl.url)
route = Rails.application.routes.recognize_path(parsed.path) route = Rails.application.routes.recognize_path(parsed.path)
if route[:topic_id].present? if route[:topic_id].present?
post = Post.where(topic_id: route[:topic_id], post_number: route[:post_number] || 1).first post = Post.find_by(topic_id: route[:topic_id], post_number: (route[:post_number] || 1))
tl.update_column(:link_post_id, post.id) if post.present? tl.update_column(:link_post_id, post.id) if post.present?
end end

View File

@ -2,8 +2,8 @@ class MoveCasSettings < ActiveRecord::Migration
def change def change
#As part of removing the build in CAS authentication we should #As part of removing the build in CAS authentication we should
#convert the data over to be used by the plugin. #convert the data over to be used by the plugin.
cas_hostname = SiteSetting.where(name: 'cas_hostname').first cas_hostname = SiteSetting.find_by(name: "cas_hostname")
cas_sso_hostname = SiteSetting.where(name: 'cas_sso_hostname').first cas_sso_hostname = SiteSetting.find_by(name: "cas_sso_hostname")
if cas_hostname && ! cas_sso_hostname if cas_hostname && ! cas_sso_hostname
#convert the setting over for use by the plugin #convert the setting over for use by the plugin
cas_hostname.update_attribute(:name, 'cas_sso_hostname') cas_hostname.update_attribute(:name, 'cas_sso_hostname')
@ -13,8 +13,8 @@ class MoveCasSettings < ActiveRecord::Migration
cas_hostname.destroy cas_hostname.destroy
end end
cas_domainname = SiteSetting.where(name: 'cas_domainname').first cas_domainname = SiteSetting.find_by(name: "cas_domainname")
cas_sso_email_domain = SiteSetting.where(name: 'cas_sso_email_domain').first cas_sso_email_domain = SiteSetting.find_by(name: "cas_sso_email_domain")
if cas_domainname && ! cas_sso_email_domain if cas_domainname && ! cas_sso_email_domain
#convert the setting over for use by the plugin #convert the setting over for use by the plugin
cas_domainname.update_attribute(:name, 'cas_sso_email_domain') cas_domainname.update_attribute(:name, 'cas_sso_email_domain')
@ -24,7 +24,7 @@ class MoveCasSettings < ActiveRecord::Migration
cas_domainname.destroy cas_domainname.destroy
end end
cas_logins = SiteSetting.where(name: 'cas_logins').first cas_logins = SiteSetting.find_by(name: "cas_logins")
if cas_logins if cas_logins
cas_logins.destroy cas_logins.destroy
end end

View File

@ -24,7 +24,7 @@ class Auth::DefaultCurrentUserProvider
current_user = nil current_user = nil
if auth_token && auth_token.length == 32 if auth_token && auth_token.length == 32
current_user = User.where(auth_token: auth_token).first current_user = User.find_by(auth_token: auth_token)
end end
if current_user && (current_user.suspended? || !current_user.active) if current_user && (current_user.suspended? || !current_user.active)
@ -53,7 +53,7 @@ class Auth::DefaultCurrentUserProvider
raise Discourse::InvalidAccess.new if api_username && (api_key.user.username_lower != api_username.downcase) raise Discourse::InvalidAccess.new if api_username && (api_key.user.username_lower != api_username.downcase)
current_user = api_key.user current_user = api_key.user
elsif api_username elsif api_username
current_user = User.where(username_lower: api_username.downcase).first current_user = User.find_by(username_lower: api_username.downcase)
end end
end end

View File

@ -17,10 +17,10 @@ class Auth::FacebookAuthenticator < Auth::Authenticator
result.extra_data = facebook_hash result.extra_data = facebook_hash
user_info = FacebookUserInfo.where(facebook_user_id: facebook_hash[:facebook_user_id]).first user_info = FacebookUserInfo.find_by(facebook_user_id: facebook_hash[:facebook_user_id])
result.user = user_info.try(:user) result.user = user_info.try(:user)
if !result.user && !email.blank? && result.user = User.where(email: Email.downcase(email)).first if !result.user && !email.blank? && result.user = User.find_by(email: Email.downcase(email))
FacebookUserInfo.create({user_id: result.user.id}.merge(facebook_hash)) FacebookUserInfo.create({user_id: result.user.id}.merge(facebook_hash))
end end

View File

@ -19,7 +19,7 @@ class Auth::GithubAuthenticator < Auth::Authenticator
github_screen_name: screen_name, github_screen_name: screen_name,
} }
user_info = GithubUserInfo.where(github_user_id: github_user_id).first user_info = GithubUserInfo.find_by(github_user_id: github_user_id)
if user_info if user_info
user = user_info.user user = user_info.user

View File

@ -20,7 +20,7 @@ class Auth::OAuth2Authenticator < Auth::Authenticator
result.email = email = data[:email] result.email = email = data[:email]
result.name = name = data[:name] result.name = name = data[:name]
oauth2_user_info = Oauth2UserInfo.where(uid: oauth2_uid, provider: oauth2_provider).first oauth2_user_info = Oauth2UserInfo.find_by(uid: oauth2_uid, provider: oauth2_provider)
if !oauth2_user_info && @opts[:trusted] && user = User.find_by_email(email) if !oauth2_user_info && @opts[:trusted] && user = User.find_by_email(email)
oauth2_user_info = Oauth2UserInfo.create(uid: oauth2_uid, oauth2_user_info = Oauth2UserInfo.create(uid: oauth2_uid,

View File

@ -21,7 +21,7 @@ class Auth::TwitterAuthenticator < Auth::Authenticator
twitter_screen_name: screen_name twitter_screen_name: screen_name
} }
user_info = TwitterUserInfo.where(twitter_user_id: twitter_user_id).first user_info = TwitterUserInfo.find_by(twitter_user_id: twitter_user_id)
result.user = user_info.try(:user) result.user = user_info.try(:user)

View File

@ -101,7 +101,7 @@ class ComposerMessagesFinder
(@user.post_count >= SiteSetting.educate_until_posts) && (@user.post_count >= SiteSetting.educate_until_posts) &&
!UserHistory.exists_for_user?(@user, :notified_about_dominating_topic, topic_id: @details[:topic_id]) !UserHistory.exists_for_user?(@user, :notified_about_dominating_topic, topic_id: @details[:topic_id])
topic = Topic.where(id: @details[:topic_id]).first topic = Topic.find_by(id: @details[:topic_id])
return if topic.blank? || return if topic.blank? ||
topic.user_id == @user.id || topic.user_id == @user.id ||
topic.posts_count < SiteSetting.summary_posts_required || topic.posts_count < SiteSetting.summary_posts_required ||
@ -127,7 +127,7 @@ class ComposerMessagesFinder
def check_reviving_old_topic def check_reviving_old_topic
return unless @details[:topic_id] return unless @details[:topic_id]
topic = Topic.where(id: @details[:topic_id]).first topic = Topic.find_by(id: @details[:topic_id])
return unless replying? return unless replying?

View File

@ -197,12 +197,12 @@ module Discourse
# Either returns the site_contact_username user or the first admin. # Either returns the site_contact_username user or the first admin.
def self.site_contact_user def self.site_contact_user
user = User.where(username_lower: SiteSetting.site_contact_username.downcase).first if SiteSetting.site_contact_username.present? user = User.find_by(username_lower: SiteSetting.site_contact_username.downcase) if SiteSetting.site_contact_username.present?
user ||= User.admins.real.order(:id).first user ||= User.admins.real.order(:id).first
end end
def self.system_user def self.system_user
User.where(id: -1).first User.find_by(id: -1)
end end
def self.store def self.store

View File

@ -65,7 +65,7 @@ module Export
end end
def ensure_we_have_a_user def ensure_we_have_a_user
@user = User.where(id: @user_id).first @user = User.find_by(id: @user_id)
raise Discourse::InvalidParameters.new(:user_id) unless @user raise Discourse::InvalidParameters.new(:user_id) unless @user
end end

View File

@ -79,7 +79,7 @@ module Import
end end
def ensure_we_have_a_user def ensure_we_have_a_user
user = User.where(id: @user_id).first user = User.find_by(id: @user_id)
raise Discourse::InvalidParameters.new(:user_id) unless user raise Discourse::InvalidParameters.new(:user_id) unless user
# keep some user data around to check them against the newly restored database # keep some user data around to check them against the newly restored database
@user_info = { id: user.id, username: user.username, email: user.email } @user_info = { id: user.id, username: user.username, email: user.email }
@ -280,7 +280,7 @@ module Import
end end
def notify_user def notify_user
if user = User.where(email: @user_info[:email]).first if user = User.find_by(email: @user_info[:email])
log "Notifying '#{user.username}' of the end of the restore..." log "Notifying '#{user.username}' of the end of the restore..."
# NOTE: will only notify if user != Discourse.site_contact_user # NOTE: will only notify if user != Discourse.site_contact_user
if @success if @success

View File

@ -23,7 +23,7 @@ module Onebox
linked = "<a href='#{@url}'>#{@url}</a>" linked = "<a href='#{@url}'>#{@url}</a>"
if route[:post_number].present? && route[:post_number].to_i > 1 if route[:post_number].present? && route[:post_number].to_i > 1
# Post Link # Post Link
post = Post.where(topic_id: route[:topic_id], post_number: route[:post_number].to_i).first post = Post.find_by(topic_id: route[:topic_id], post_number: route[:post_number].to_i)
return linked unless post return linked unless post
return linked if post.hidden return linked if post.hidden
return linked unless Guardian.new.can_see?(post) return linked unless Guardian.new.can_see?(post)

View File

@ -105,7 +105,7 @@ class PostCreator
def self.set_reply_user_id(post) def self.set_reply_user_id(post)
return unless post.reply_to_post_number.present? return unless post.reply_to_post_number.present?
post.reply_to_user_id ||= Post.select(:user_id).where(topic_id: post.topic_id, post_number: post.reply_to_post_number).first.try(:user_id) post.reply_to_user_id ||= Post.select(:user_id).find_by(topic_id: post.topic_id, post_number: post.reply_to_post_number).try(:user_id)
end end
protected protected
@ -148,15 +148,11 @@ class PostCreator
def clear_possible_flags(topic) def clear_possible_flags(topic)
# at this point we know the topic is a PM and has been replied to ... check if we need to clear any flags # at this point we know the topic is a PM and has been replied to ... check if we need to clear any flags
# #
first_post = Post.select(:id).where(topic_id: topic.id).where('post_number = 1').first first_post = Post.select(:id).where(topic_id: topic.id).find_by("post_number = 1")
post_action = nil post_action = nil
if first_post if first_post
post_action = PostAction.where( post_action = PostAction.find_by(related_post_id: first_post.id, deleted_at: nil, post_action_type_id: PostActionType.types[:notify_moderators])
related_post_id: first_post.id,
deleted_at: nil,
post_action_type_id: PostActionType.types[:notify_moderators]
).first
end end
if post_action if post_action
@ -179,7 +175,7 @@ class PostCreator
raise ex raise ex
end end
else else
topic = Topic.where(id: @opts[:topic_id]).first topic = Topic.find_by(id: @opts[:topic_id])
guardian.ensure_can_create!(Post, topic) guardian.ensure_can_create!(Post, topic)
end end
@topic = topic @topic = topic

View File

@ -116,7 +116,7 @@ class PostRevisor
return unless @post.post_number == 1 return unless @post.post_number == 1
# Is there a category with our topic id? # Is there a category with our topic id?
category = Category.where(topic_id: @post.topic_id).first category = Category.find_by(topic_id: @post.topic_id)
return unless category.present? return unless category.present?
# If found, update its description # If found, update its description

View File

@ -23,7 +23,7 @@ module PrettyText
def avatar_template(username) def avatar_template(username)
return "" unless username return "" unless username
user = User.where(username_lower: username.downcase).first user = User.find_by(username_lower: username.downcase)
user.avatar_template if user.present? user.avatar_template if user.present?
end end

View File

@ -109,7 +109,7 @@ class Search
# If we're searching for a single topic # If we're searching for a single topic
def single_topic(id) def single_topic(id)
topic = Topic.where(id: id).first topic = Topic.find_by(id: id)
return nil unless @guardian.can_see?(topic) return nil unless @guardian.can_see?(topic)
@results.add_result(SearchResult.from_topic(topic)) @results.add_result(SearchResult.from_topic(topic))

View File

@ -20,7 +20,7 @@ module SiteContentClassMethods
replacements = {site_name: SiteSetting.title}.merge!(replacements) replacements = {site_name: SiteSetting.title}.merge!(replacements)
replacements = SiteSetting.settings_hash.merge!(replacements) replacements = SiteSetting.settings_hash.merge!(replacements)
site_content = SiteContent.select(:content).where(content_type: content_type).first site_content = SiteContent.select(:content).find_by(content_type: content_type)
result = "" result = ""
if site_content.blank? if site_content.blank?
@ -39,7 +39,7 @@ module SiteContentClassMethods
def find_or_new(content_type) def find_or_new(content_type)
site_content = SiteContent.where(content_type: content_type).first site_content = SiteContent.find_by(content_type: content_type)
return site_content if site_content.present? return site_content if site_content.present?
site_content = SiteContent.new site_content = SiteContent.new

View File

@ -72,9 +72,9 @@ class TopicCreator
# When all clients are updated the category variable should # When all clients are updated the category variable should
# be set directly to the contents of the if statement. # be set directly to the contents of the if statement.
if (@opts[:category].is_a? Integer) || (@opts[:category] =~ /^\d+$/) if (@opts[:category].is_a? Integer) || (@opts[:category] =~ /^\d+$/)
Category.where(id: @opts[:category]).first Category.find_by(id: @opts[:category])
else else
Category.where(name: @opts[:category]).first Category.find_by(name: @opts[:category])
end end
end end

View File

@ -46,7 +46,7 @@ class TopicRetriever
end end
def fetch_http def fetch_http
user = User.where(username_lower: SiteSetting.embed_by_username.downcase).first user = User.find_by(username_lower: SiteSetting.embed_by_username.downcase)
return if user.blank? return if user.blank?
TopicEmbed.import_remote(user, @embed_url) TopicEmbed.import_remote(user, @embed_url)

View File

@ -185,7 +185,7 @@ class TopicView
def topic_user def topic_user
@topic_user ||= begin @topic_user ||= begin
return nil if @user.blank? return nil if @user.blank?
@topic.topic_users.where(user_id: @user.id).first @topic.topic_users.find_by(user_id: @user.id)
end end
end end

View File

@ -167,7 +167,7 @@ describe PostCreator do
first_post = creator.create first_post = creator.create
# ensure topic user is correct # ensure topic user is correct
topic_user = first_post.user.topic_users.where(topic_id: first_post.topic_id).first topic_user = first_post.user.topic_users.find_by(topic_id: first_post.topic_id)
topic_user.should be_present topic_user.should be_present
topic_user.should be_posted topic_user.should be_posted
topic_user.last_read_post_number.should == first_post.post_number topic_user.last_read_post_number.should == first_post.post_number

View File

@ -164,7 +164,7 @@ describe PostDestroyer do
context 'topic_user' do context 'topic_user' do
let(:topic_user) { second_user.topic_users.where(topic_id: topic.id).first } let(:topic_user) { second_user.topic_users.find_by(topic_id: topic.id) }
it 'clears the posted flag for the second user' do it 'clears the posted flag for the second user' do
topic_user.posted?.should be_false topic_user.posted?.should be_false
@ -275,8 +275,8 @@ describe PostDestroyer do
it "should delete the post actions" do it "should delete the post actions" do
flag = PostAction.act(codinghorror, second_post, PostActionType.types[:off_topic]) flag = PostAction.act(codinghorror, second_post, PostActionType.types[:off_topic])
PostDestroyer.new(moderator, second_post).destroy PostDestroyer.new(moderator, second_post).destroy
expect(PostAction.where(id: flag.id).first).to be_nil expect(PostAction.find_by(id: flag.id)).to be_nil
expect(PostAction.where(id: bookmark.id).first).to be_nil expect(PostAction.find_by(id: bookmark.id)).to be_nil
end end
it 'should update flag counts on the post' do it 'should update flag counts on the post' do

View File

@ -10,7 +10,7 @@ describe PrettyText do
before(:each) do before(:each) do
eviltrout = User.new eviltrout = User.new
eviltrout.stubs(:avatar_template).returns("http://test.localhost/uploads/default/avatars/42d/57c/46ce7ee487/{size}.png") eviltrout.stubs(:avatar_template).returns("http://test.localhost/uploads/default/avatars/42d/57c/46ce7ee487/{size}.png")
User.expects(:where).with(username_lower: "eviltrout").returns([eviltrout]) User.expects(:find_by).with(username_lower: "eviltrout").returns(eviltrout)
end end
it "produces a quote even with new lines in it" do it "produces a quote even with new lines in it" do

View File

@ -57,7 +57,7 @@ describe CategoriesController do
} }
response.status.should == 200 response.status.should == 200
category = Category.where(name: "hello").first category = Category.find_by(name: "hello")
category.category_groups.map{|g| [g.group_id, g.permission_type]}.sort.should == [ category.category_groups.map{|g| [g.group_id, g.permission_type]}.sort.should == [
[Group[:everyone].id, readonly],[Group[:staff].id,create_post] [Group[:everyone].id, readonly],[Group[:staff].id,create_post]
] ]

View File

@ -171,7 +171,7 @@ describe SessionController do
context 'when email is confirmed' do context 'when email is confirmed' do
before do before do
token = user.email_tokens.where(email: user.email).first token = user.email_tokens.find_by(email: user.email)
EmailToken.confirm(token.token) EmailToken.confirm(token.token)
end end

View File

@ -116,20 +116,20 @@ describe UploadsController do
it "returns 404 when using external storage" do it "returns 404 when using external storage" do
store = stub(internal?: false) store = stub(internal?: false)
Discourse.stubs(:store).returns(store) Discourse.stubs(:store).returns(store)
Upload.expects(:where).never Upload.expects(:find_by).never
get :show, site: "default", id: 1, sha: "1234567890abcdef", extension: "pdf" get :show, site: "default", id: 1, sha: "1234567890abcdef", extension: "pdf"
response.response_code.should == 404 response.response_code.should == 404
end end
it "returns 404 when the upload doens't exist" do it "returns 404 when the upload doens't exist" do
Upload.expects(:where).with(id: 2, url: "/uploads/default/2/1234567890abcdef.pdf").returns [nil] Upload.expects(:find_by).with(id: 2, url: "/uploads/default/2/1234567890abcdef.pdf").returns(nil)
get :show, site: "default", id: 2, sha: "1234567890abcdef", extension: "pdf" get :show, site: "default", id: 2, sha: "1234567890abcdef", extension: "pdf"
response.response_code.should == 404 response.response_code.should == 404
end end
it 'uses send_file' do it 'uses send_file' do
upload = build(:upload) upload = build(:upload)
Upload.expects(:where).with(id: 42, url: "/uploads/default/42/66b3ed1503efc936.zip").returns([upload]) Upload.expects(:find_by).with(id: 42, url: "/uploads/default/42/66b3ed1503efc936.zip").returns(upload)
controller.stubs(:render) controller.stubs(:render)
controller.expects(:send_file) controller.expects(:send_file)

View File

@ -45,7 +45,7 @@ describe UserBadgesController do
StaffActionLogger.any_instance.expects(:log_badge_grant).once StaffActionLogger.any_instance.expects(:log_badge_grant).once
xhr :post, :create, badge_id: badge.id, username: user.username xhr :post, :create, badge_id: badge.id, username: user.username
response.status.should == 200 response.status.should == 200
user_badge = UserBadge.where(user: user, badge: badge).first user_badge = UserBadge.find_by(user: user, badge: badge)
user_badge.should be_present user_badge.should be_present
user_badge.granted_by.should eq(admin) user_badge.granted_by.should eq(admin)
end end
@ -61,7 +61,7 @@ describe UserBadgesController do
StaffActionLogger.any_instance.expects(:log_badge_grant).never StaffActionLogger.any_instance.expects(:log_badge_grant).never
xhr :post, :create, badge_id: badge.id, username: user.username, api_key: api_key.key xhr :post, :create, badge_id: badge.id, username: user.username, api_key: api_key.key
response.status.should == 200 response.status.should == 200
user_badge = UserBadge.where(user: user, badge: badge).first user_badge = UserBadge.find_by(user: user, badge: badge)
user_badge.should be_present user_badge.should be_present
user_badge.granted_by.should eq(Discourse.system_user) user_badge.granted_by.should eq(Discourse.system_user)
end end
@ -80,7 +80,7 @@ describe UserBadgesController do
StaffActionLogger.any_instance.expects(:log_badge_revoke).once StaffActionLogger.any_instance.expects(:log_badge_revoke).once
xhr :delete, :destroy, id: user_badge.id xhr :delete, :destroy, id: user_badge.id
response.status.should == 200 response.status.should == 200
UserBadge.where(id: user_badge.id).first.should be_nil UserBadge.find_by(id: user_badge.id).should be_nil
end end
end end
end end

View File

@ -382,7 +382,7 @@ describe UsersController do
end end
it 'should not result in an active account' do it 'should not result in an active account' do
User.where(username: @user.username).first.active.should be_false User.find_by(username: @user.username).active.should be_false
end end
end end

View File

@ -8,16 +8,16 @@ describe Jobs::CloseTopic do
it 'closes a topic that is set to auto-close' do it 'closes a topic that is set to auto-close' do
topic = Fabricate.build(:topic, auto_close_at: Time.zone.now, user: admin) topic = Fabricate.build(:topic, auto_close_at: Time.zone.now, user: admin)
topic.expects(:update_status).with('autoclosed', true, admin) topic.expects(:update_status).with('autoclosed', true, admin)
Topic.stubs(:where).returns([topic]) Topic.stubs(:find_by).returns(topic)
User.stubs(:where).returns([admin]) User.stubs(:find_by).returns(admin)
Jobs::CloseTopic.new.execute( topic_id: 123, user_id: 234 ) Jobs::CloseTopic.new.execute( topic_id: 123, user_id: 234 )
end end
shared_examples_for "cases when CloseTopic does nothing" do shared_examples_for "cases when CloseTopic does nothing" do
it 'does nothing to the topic' do it 'does nothing to the topic' do
topic.expects(:update_status).never topic.expects(:update_status).never
Topic.stubs(:where).returns([topic]) Topic.stubs(:find_by).returns(topic)
User.stubs(:where).returns([admin]) User.stubs(:find_by).returns(admin)
Jobs::CloseTopic.new.execute( topic_id: 123, user_id: 234 ) Jobs::CloseTopic.new.execute( topic_id: 123, user_id: 234 )
end end
end end

View File

@ -240,7 +240,7 @@ describe Invite do
end end
context 'invited by another user to the same topic' do context 'invited by another user to the same topic' do
let(:coding_horror) { User.where(username: 'CodingHorror').first } let(:coding_horror) { User.find_by(username: "CodingHorror") }
let!(:another_invite) { topic.invite(coding_horror, 'jake@adventuretime.ooo') } let!(:another_invite) { topic.invite(coding_horror, 'jake@adventuretime.ooo') }
let!(:user) { invite.redeem } let!(:user) { invite.redeem }
@ -250,7 +250,7 @@ describe Invite do
end end
context 'invited by another user to a different topic' do context 'invited by another user to a different topic' do
let(:coding_horror) { User.where(username: 'CodingHorror').first } let(:coding_horror) { User.find_by(username: "CodingHorror") }
let(:another_topic) { Fabricate(:topic, archetype: "private_message", user: coding_horror) } let(:another_topic) { Fabricate(:topic, archetype: "private_message", user: coding_horror) }
let!(:another_invite) { another_topic.invite(coding_horror, 'jake@adventuretime.ooo') } let!(:another_invite) { another_topic.invite(coding_horror, 'jake@adventuretime.ooo') }
let!(:user) { invite.redeem } let!(:user) { invite.redeem }

View File

@ -61,7 +61,7 @@ describe PostMover do
let!(:new_topic) { topic.move_posts(user, [p2.id, p4.id], title: "new testing topic name", category_id: category.id) } let!(:new_topic) { topic.move_posts(user, [p2.id, p4.id], title: "new testing topic name", category_id: category.id) }
it "works correctly" do it "works correctly" do
TopicUser.where(user_id: user.id, topic_id: topic.id).first.last_read_post_number.should == p3.post_number TopicUser.find_by(user_id: user.id, topic_id: topic.id).last_read_post_number.should == p3.post_number
new_topic.should be_present new_topic.should be_present
new_topic.featured_user1_id.should == another_user.id new_topic.featured_user1_id.should == another_user.id
@ -93,7 +93,7 @@ describe PostMover do
topic.highest_post_number.should == p3.post_number topic.highest_post_number.should == p3.post_number
# both the like and was_liked user actions should be correct # both the like and was_liked user actions should be correct
action = UserAction.where(user_id: another_user.id).first action = UserAction.find_by(user_id: another_user.id)
action.target_topic_id.should == new_topic.id action.target_topic_id.should == new_topic.id
end end
end end
@ -137,7 +137,7 @@ describe PostMover do
topic.highest_post_number.should == p3.post_number topic.highest_post_number.should == p3.post_number
# Should update last reads # Should update last reads
TopicUser.where(user_id: user.id, topic_id: topic.id).first.last_read_post_number.should == p3.post_number TopicUser.find_by(user_id: user.id, topic_id: topic.id).last_read_post_number.should == p3.post_number
end end
end end

View File

@ -48,15 +48,15 @@ describe PostTiming do
PostTiming.where(topic_id: topic_id, user_id: 2, post_number: 3).count.should == 1 PostTiming.where(topic_id: topic_id, user_id: 2, post_number: 3).count.should == 1
PostTiming.where(topic_id: topic_id, user_id: 3, post_number: 3).count.should == 1 PostTiming.where(topic_id: topic_id, user_id: 3, post_number: 3).count.should == 1
tu = TopicUser.where(topic_id: topic_id, user_id: 1).first tu = TopicUser.find_by(topic_id: topic_id, user_id: 1)
tu.last_read_post_number.should == 1 tu.last_read_post_number.should == 1
tu.seen_post_count.should == 1 tu.seen_post_count.should == 1
tu = TopicUser.where(topic_id: topic_id, user_id: 2).first tu = TopicUser.find_by(topic_id: topic_id, user_id: 2)
tu.last_read_post_number.should == 3 tu.last_read_post_number.should == 3
tu.seen_post_count.should == 3 tu.seen_post_count.should == 3
tu = TopicUser.where(topic_id: topic_id, user_id: 3).first tu = TopicUser.find_by(topic_id: topic_id, user_id: 3)
tu.last_read_post_number.should == 3 tu.last_read_post_number.should == 3
tu.seen_post_count.should == 3 tu.seen_post_count.should == 3
@ -113,7 +113,7 @@ describe PostTiming do
before do before do
PostTiming.record_timing(@timing_attrs) PostTiming.record_timing(@timing_attrs)
PostTiming.record_timing(@timing_attrs) PostTiming.record_timing(@timing_attrs)
@timing = PostTiming.where(topic_id: @post.topic_id, user_id: @coding_horror.id, post_number: @post.post_number).first @timing = PostTiming.find_by(topic_id: @post.topic_id, user_id: @coding_horror.id, post_number: @post.post_number)
end end
it 'creates a timing record' do it 'creates a timing record' do

View File

@ -282,7 +282,7 @@ describe Topic do
context 'private message' do context 'private message' do
let(:coding_horror) { User.where(username: 'CodingHorror').first } let(:coding_horror) { User.find_by(username: "CodingHorror") }
let(:evil_trout) { Fabricate(:evil_trout) } let(:evil_trout) { Fabricate(:evil_trout) }
let(:topic) { Fabricate(:private_message_topic) } let(:topic) { Fabricate(:private_message_topic) }
@ -670,7 +670,7 @@ describe Topic do
it 'updates the last_post_user_id to the second_user' do it 'updates the last_post_user_id to the second_user' do
@topic.last_post_user_id.should == @second_user.id @topic.last_post_user_id.should == @second_user.id
@topic.last_posted_at.to_i.should == @new_post.created_at.to_i @topic.last_posted_at.to_i.should == @new_post.created_at.to_i
topic_user = @second_user.topic_users.where(topic_id: @topic.id).first topic_user = @second_user.topic_users.find_by(topic_id: @topic.id)
topic_user.posted?.should be_true topic_user.posted?.should be_true
end end

View File

@ -23,7 +23,7 @@ describe TopicStatusUpdate do
post.topic.posts.count.should == 2 post.topic.posts.count.should == 2
tu = TopicUser.where(user_id: user.id).first tu = TopicUser.find_by(user_id: user.id)
tu.last_read_post_number.should == 2 tu.last_read_post_number.should == 2
end end
end end

View File

@ -263,7 +263,7 @@ describe TopicUser do
TopicUser.ensure_consistency! TopicUser.ensure_consistency!
tu = TopicUser.where(user_id: p1.user_id, topic_id: p1.topic_id).first tu = TopicUser.find_by(user_id: p1.user_id, topic_id: p1.topic_id)
tu.last_read_post_number.should == p2.post_number tu.last_read_post_number.should == p2.post_number
tu.seen_post_count.should == 2 tu.seen_post_count.should == 2
end end
@ -278,15 +278,15 @@ describe TopicUser do
create_post(topic_id: post.topic_id) create_post(topic_id: post.topic_id)
# mails posts from earlier topics # mails posts from earlier topics
tu = TopicUser.where(user_id: user3.id, topic_id: post.topic_id).first tu = TopicUser.find_by(user_id: user3.id, topic_id: post.topic_id)
tu.last_emailed_post_number.should == 2 tu.last_emailed_post_number.should == 2
# mails nothing to random users # mails nothing to random users
tu = TopicUser.where(user_id: user1.id, topic_id: post.topic_id).first tu = TopicUser.find_by(user_id: user1.id, topic_id: post.topic_id)
tu.should be_nil tu.should be_nil
# mails other user # mails other user
tu = TopicUser.where(user_id: user2.id, topic_id: post.topic_id).first tu = TopicUser.find_by(user_id: user2.id, topic_id: post.topic_id)
tu.last_emailed_post_number.should == 2 tu.last_emailed_post_number.should == 2
end end
end end

View File

@ -49,7 +49,7 @@ describe Upload do
context "#create_for" do context "#create_for" do
it "does not create another upload if it already exists" do it "does not create another upload if it already exists" do
Upload.expects(:where).with(sha1: image_sha1).returns([upload]) Upload.expects(:find_by).with(sha1: image_sha1).returns(upload)
Upload.expects(:save).never Upload.expects(:save).never
Upload.create_for(user_id, image, image_filename, image_filesize).should == upload Upload.create_for(user_id, image, image_filename, image_filesize).should == upload
end end
@ -95,18 +95,18 @@ describe Upload do
context ".get_from_url" do context ".get_from_url" do
it "works when the file has been uploaded" do it "works when the file has been uploaded" do
Upload.expects(:where).returns([]).once Upload.expects(:find_by).returns(nil).once
Upload.get_from_url("/uploads/default/1/10387531.jpg") Upload.get_from_url("/uploads/default/1/10387531.jpg")
end end
it "works when using a cdn" do it "works when using a cdn" do
Rails.configuration.action_controller.stubs(:asset_host).returns("http://my.cdn.com") Rails.configuration.action_controller.stubs(:asset_host).returns("http://my.cdn.com")
Upload.expects(:where).with(url: "/uploads/default/1/02395732905.jpg").returns([]).once Upload.expects(:find_by).with(url: "/uploads/default/1/02395732905.jpg").returns(nil).once
Upload.get_from_url("http://my.cdn.com/uploads/default/1/02395732905.jpg") Upload.get_from_url("http://my.cdn.com/uploads/default/1/02395732905.jpg")
end end
it "works only when the file has been uploaded" do it "works only when the file has been uploaded" do
Upload.expects(:where).never Upload.expects(:find_by).never
Upload.get_from_url("http://domain.com/my/file.txt") Upload.get_from_url("http://domain.com/my/file.txt")
end end

View File

@ -116,8 +116,8 @@ describe UserAction do
context "successful like" do context "successful like" do
before do before do
PostAction.act(liker, post, PostActionType.types[:like]) PostAction.act(liker, post, PostActionType.types[:like])
@liker_action = liker.user_actions.where(action_type: UserAction::LIKE).first @liker_action = liker.user_actions.find_by(action_type: UserAction::LIKE)
@likee_action = likee.user_actions.where(action_type: UserAction::WAS_LIKED).first @likee_action = likee.user_actions.find_by(action_type: UserAction::WAS_LIKED)
end end
it 'should result in correct data assignment' do it 'should result in correct data assignment' do
@ -160,7 +160,7 @@ describe UserAction do
describe 'topic action' do describe 'topic action' do
before do before do
@action = @post.user.user_actions.where(action_type: UserAction::NEW_TOPIC).first @action = @post.user.user_actions.find_by(action_type: UserAction::NEW_TOPIC)
end end
it 'should exist' do it 'should exist' do
@action.should_not be_nil @action.should_not be_nil
@ -169,7 +169,7 @@ describe UserAction do
end end
it 'should not log a post user action' do it 'should not log a post user action' do
@post.user.user_actions.where(action_type: UserAction::REPLY).first.should be_nil @post.user.user_actions.find_by(action_type: UserAction::REPLY).should be_nil
end end
@ -183,9 +183,9 @@ describe UserAction do
end end
it 'should log user actions correctly' do it 'should log user actions correctly' do
@response.user.user_actions.where(action_type: UserAction::REPLY).first.should_not be_nil @response.user.user_actions.find_by(action_type: UserAction::REPLY).should_not be_nil
@post.user.user_actions.where(action_type: UserAction::RESPONSE).first.should_not be_nil @post.user.user_actions.find_by(action_type: UserAction::RESPONSE).should_not be_nil
@mentioned.user_actions.where(action_type: UserAction::MENTION).first.should_not be_nil @mentioned.user_actions.find_by(action_type: UserAction::MENTION).should_not be_nil
@post.user.user_actions.joins(:target_post).where('posts.post_number = 2').count.should == 1 @post.user.user_actions.joins(:target_post).where('posts.post_number = 2').count.should == 1
end end
@ -203,7 +203,7 @@ describe UserAction do
@post = Fabricate(:post) @post = Fabricate(:post)
@user = @post.user @user = @post.user
PostAction.act(@user, @post, PostActionType.types[:bookmark]) PostAction.act(@user, @post, PostActionType.types[:bookmark])
@action = @user.user_actions.where(action_type: UserAction::BOOKMARK).first @action = @user.user_actions.find_by(action_type: UserAction::BOOKMARK)
end end
it 'should create a bookmark action correctly' do it 'should create a bookmark action correctly' do
@ -213,7 +213,7 @@ describe UserAction do
@action.user_id.should == @user.id @action.user_id.should == @user.id
PostAction.remove_act(@user, @post, PostActionType.types[:bookmark]) PostAction.remove_act(@user, @post, PostActionType.types[:bookmark])
@user.user_actions.where(action_type: UserAction::BOOKMARK).first.should be_nil @user.user_actions.find_by(action_type: UserAction::BOOKMARK).should be_nil
end end
end end

Some files were not shown because too many files have changed in this diff Show More