ruby - Rails passing in variables into view helper methods from form selection -
i have bit of code in user.rb model this:
def self.aggregate(articles) array = [] articles.each |a| array << { :id => a.nid, :views => a.daily_view_metrics.sum_views(a.nid), :date => a.daily_view_metrics.latest_date(a.nid), :title => a.daily_view_metrics.latest_title(a.nid), :visits => a.daily_view_metrics.sum_visits(a.nid) } end return array end in user_controller pass show method @metrics = user.aggregate(@articles) (@articles being subset of articles user)
now in view (user#show) call @metrics.each |m| , output different things in table. according video seems link_to method url parameter seems best way have users dynamically switch want sort against.
how can input url parameter sort array? tried calling @metrics.sort_by{|h| h[params[:sort]]}.each |m| :sort being url parameter links (i.e. views table header link click passes :sort => ":views" in. trying sort_by{|h| h[:views]} since works fine sorting array. nothing happens. array isn't sorted.
edit:
i solved making aggregate method pass key in string (i.e. "id" opposed :id). url params works beautifully.
<%= link_to "views", :sort => "views"%> sorts views in ascending order.
to order in descending mode can negate - element using sort by. ordering ascending , revert collection inefficient.
for instance
$> [{a: 'a1', b: 1}, {a: 'a2', b: 2}].sort_by{ |h| -h[:b] } # => [{:a=>"a2", :b=>2}, {:a=>"a1", :b=>1}] $> [{a: 'a1', b: 1}, {a: 'a2', b: 2}].sort_by{ |h| h[:b] } # => [{:a=>"a1", :b=>1}, {:a=>"a2", :b=>2}] in form of view, have (a radiobutton e.g select or whatever prefer):
<%= radio_button_tag 'radio_order', 'ascending', true %> ascending <%= radio_button_tag 'radio_order', 'descending' %> descending <%= submit_tag "order" %> then in helper value using params[:radio_order]:
aggregate('views', params[:radio_order])
Comments
Post a Comment