Skip to content

Commit

Permalink
Update sql in Rails way
Browse files Browse the repository at this point in the history
  • Loading branch information
chansuke committed Jun 23, 2017
1 parent 629ef98 commit a5239ae
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions app/models/vote_on_issue.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
class VoteOnIssue < ActiveRecord::Base
unloadable

# Every vote belongs to a user and an issue
belongs_to :user
belongs_to :issue


scope :left_join_user, -> { joins("LEFT JOIN users ON users.id = vote_on_issues.user_id").select("users.login") }
scope :up_voters, -> { select(:vote_val).where("vote_val > ?", 0) }
scope :down_voters, -> { select(:vote_val).where("vote_val < ?", 0) }
scope :order_by_login, -> { order("users.login ASC") }

def self.getMyVote(issue)
iRet = 0
begin
Expand All @@ -15,30 +20,21 @@ def self.getMyVote(issue)
end
iRet
end

def self.getUpVoteCountOnIssue(issue_id)
where("issue_id = ? AND vote_val > 0", issue_id).count
end

def self.getDnVoteCountOnIssue(issue_id)
where("issue_id = ? AND vote_val < 0", issue_id).count
end

def self.getListOfUpVotersOnIssue(issue_id)
# this does load the users, but costly: One query for each user
# where("issue_id = ? AND vote_val > 0", issue_id)
# this does load the users, less costly: One query for all users
# includes(:user).where("issue_id = ? AND vote_val > 0", issue_id)
# where("issue_id = ? AND vote_val > 0", issue_id).includes(:user)
# joins users successfully, but still execs one query for each user
# where("issue_id = ? AND vote_val > 0", issue_id).joins(:user)
# This does what I want, but I'd love to find out how to do this in rails...
find_by_sql( ["SELECT `vote_on_issues`.`vote_val` AS vote_val, `users`.`login` AS user_login FROM `vote_on_issues` LEFT JOIN `users` ON (`users`.`id` = `vote_on_issues`.`user_id`) WHERE (`issue_id` = ? AND `vote_val` > 0) ORDER BY user_login ASC", issue_id] )
VoteOnIssue.up_voters.left_join_user.order_by_login
end

def self.getListOfDnVotersOnIssue(issue_id)
# see getListOfUpVotersOnIssue
find_by_sql( ["SELECT `vote_on_issues`.`vote_val` AS vote_val, `users`.`login` AS user_login FROM `vote_on_issues` LEFT JOIN `users` ON (`users`.`id` = `vote_on_issues`.`user_id`) WHERE (`issue_id` = ? AND `vote_val` < 0) ORDER BY user_login ASC", issue_id] )
VoteOnIssue.down_voters.left_join_user.order_by_login
end

end

0 comments on commit a5239ae

Please sign in to comment.