ruby on rails - ActiveRecord - How to `select` polymorphic join as a boolean? -
i've been banging head against wall attempting come query, figured time post here.
i have class called flair
-- it's polymorphic, since lots of things can have flair:
class flair < activerecord::base belongs_to :flairable, polymorphic: true, touch: true belongs_to :user end
and comment
has many flairs
:
class comment < activerecord::base has_many :flairs, as: :flairable end
when getting list of comments, want know ones have flair belongs given user.
the best i've been able come far is
# don't worry interpolation; example # , assume have valid @comments , user_id @comments.select('comments.*'). select('flairs.id has_flaired'). joins("left join flairs on flairable_id = comments.id , flairs.user_id = #{user_id}")
but returns 1 result every flair on comment (as expected left join), multiplying number of appearances of each comment in array number of flairs has.
i've tried using distinct on (user_id)
, applying limit
, etc., efforts turn syntax errors.
can offer guidance? useful pointer somewhere in docs has examples bit more involved ones offered here: http://www.postgresql.org/docs/9.4/static/sql-select.html. i've tried suggestions @ http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html, nothing seems stick.
thanks!
section 7.2.1.3 in www.postgresql.org/docs/9.4/static/queries-table-expressions.html , first example here, , extremely patient boss ended helping problem. in end (after banging on keyboard while), managed please postgres/activerecord gods syntactically correct query (we're sanitizing user_id
before passing joins
statement.
@comments.select( "comments.*, flairs.id has_flaired" ).joins( "left join flairs on flairs.id = ( select id flairs flairs.user_id = #{user_id} , flairs.flairable_id = comments.id limit 1 )" )
this works because i'm interested in whether or not row user , flairable_id exists in flairs table, check table in subquery , use results in main query.
it makes sense i've written out, i'll leave here in case else gets flummoxed.
Comments
Post a Comment