decidim-proposals/app/controllers/decidim/proposals/proposals_controller.rb in decidim-0.0.3 vs decidim-proposals/app/controllers/decidim/proposals/proposals_controller.rb in decidim-0.0.4
- old
+ new
@@ -5,25 +5,36 @@
# Exposes the proposal resource so users can view and create them.
class ProposalsController < Decidim::Proposals::ApplicationController
include FormFactory
include FilterResource
+ helper_method :order, :random_seed
+
before_action :authenticate_user!, only: [:new, :create]
def show
@proposal = Proposal.where(feature: current_feature).find(params[:id])
end
def index
@proposals = search
.results
.includes(:author)
- .includes(votes: [:author])
- .page(params[:page])
- .per(12)
+ .includes(:category)
+ .includes(:scope)
- @random_seed = search.random_seed
+ @proposals = @proposals.page(params[:page]).per(12)
+ @proposals = reorder(@proposals)
+
+ @voted_proposals = if current_user
+ ProposalVote.where(
+ author: current_user,
+ proposal: @proposals
+ ).pluck(:decidim_proposal_id)
+ else
+ []
+ end
end
def new
authorize! :create, Proposal
@@ -48,10 +59,35 @@
end
end
private
+ def order
+ @order = params[:order] || "random"
+ end
+
+ # Returns: A random float number between -1 and 1 to be used as a random seed at the database.
+ def random_seed
+ @random_seed ||= (params[:random_seed] ? params[:random_seed].to_f : (rand * 2 - 1))
+ end
+
+ def reorder(proposals)
+ case order
+ when "random"
+ Proposal.transaction do
+ Proposal.connection.execute("SELECT setseed(#{Proposal.connection.quote(random_seed)})")
+ proposals.order("RANDOM()").load
+ end
+ when "most_voted"
+ proposals.order(proposal_votes_count: :desc)
+ when "recent"
+ proposals.order(created_at: :desc)
+ else
+ proposals
+ end
+ end
+
def search_klass
ProposalSearch
end
def default_filter_params
@@ -59,10 +95,11 @@
search_text: "",
origin: "all",
activity: "",
category_id: "",
state: "all",
- random_seed: params[:random_seed]
+ scope_id: "",
+ related_to: ""
}
end
end
end
end