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

Update sql in rails way #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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