ruby - Rails - Select, join, and order -
i trying order assets appearing in descending order based off of number of users. code works in postgres, doesn't seem working in ruby. not sure wrong. appreciated. thank in advance.
def order_assets @asset = asset.select("assets.id, count(assets_users.asset_id) the_count") .joins("left outer join assets_users on assets.id = assets_users.asset_id") .group("assets.id") .having("count(*) > 0") .order("the_count") end
i want of yellow'd assets on top, when ones users filled in below.
postgres code:
select assets.id, count(assets_users.asset_id) the_count assets left outer join assets_users on assets.id = assets_users.asset_id group assets.id having count(*) > 0 order the_count;
this how postgres comes out:
ended moving on asset model. post code under answer's code, if needs/wants it.
i first switched assets.id
assets.*
, because there asset_profile_id
parameter wasn't going through. included .where
function, query know asset_profile
assets
from. other thing added in additional ordering assets, remainders ordered based off of id number.
def set_assets @assets = asset.select("assets.*, count(assets_users.asset_id) the_count").joins("left outer join assets_users on assets.id = assets_users.asset_id").where(asset_profile_id: params[:id]).group("assets.id").having("count(*) > 0").order("the_count asc, assets.id asc") end
i ended moving code on scope within asset model:
scope :ordered_by_user_count, -> (profile_id) { select("assets.*, count(assets_users.asset_id) the_count") .joins("left outer join assets_users on assets.id = assets_users.asset_id") .where(asset_profile_id: profile_id) .group("assets.id") .having("count(*) > 0") .order("the_count asc, assets.id asc") }
thank guys steering me in right direction.
Comments
Post a Comment