ruby - Rails subquery always returns nil value -
i need count rows other table in subselect, use query:
follows_sql = follow.where(followable_type: 'idea').where('follows.followable_id = ideas.id').select('count(followable_id)').to_sql idea = idea.select("(#{follows_sql}) fcnt").includes(:collaborations). where(collaborations: { user_id: 4, owner: true })
so produced valid sql, cant access 'fcnt' value idea var. tried in different ways like:
idea[0].fcnt # return nil idea[0]["fcnt"] # return nil
but can access fields exists in idea model. how can access custom 'fcnt' field?
i think along following should work you
idea = idea.select("ideas.*, count(follows.id) fcnt").joins("left outer join follows on follows.followable_id = ideas.id").group("ideas.id") ideas.each |idea| puts idea.fcnt # should output number end
note i've left out other includes , clauses. try solve problem first, , if query works out, add in additional clauses.
also, if setup relations correctly, such idea has many follows, clean code doing like
ideas = idea.includes(:collaborations).where(collaborations: { user_id: 4, owner: true }) ideas.map { |idea| idea.follows.count }
Comments
Post a Comment