HackerTrans
TopNewTrendsCommentsPastAskShowJobs

rurabe

no profile record

comments

rurabe
·3 jaar geleden·discuss
Looks so promising, what's the timeline for something like MUI?
rurabe
·4 jaar geleden·discuss
It's not perfect or painless but I think jsonapi-serializer is pretty good
rurabe
·4 jaar geleden·discuss
Big fan of raw sql, but practically speaking (as it relates to developing with rails) CTEs can be rewritten as subqueries, the advantage being that they are linear instead of nested in SQL.

With AR queries you can do the same and make it linear in ruby (and then the computer doesn't really care if your sql is nested)

    last_three_posts = Post.limit(3).order(created_at: :desc)
    @posts = Comment.where(post_id: last_three_posts)
rurabe
·4 jaar geleden·discuss
The problem here is that you are loading all the votes as AR instances which is fine at small scale, but as your app gets larger, loading and instantiating thousands of Vote instances just to then break them down into an integer will start to drag on your controller.

If you can count in the database itself it's a big win. Although no doubt your solution is cleaner code.
rurabe
·4 jaar geleden·discuss
One neat trick that I think is relatively lesser known is that you can select arbitrary sql expressions in ActiveRecord and those values are made available on the instances.

(Also I think the above sql needs to be tweaked since you need the votes count grouped by comment not by post)

A one to many relationship in pure SQL is an awkward fit with a Rails app as it requires serializing (at least) the many as json. Then there's this weird conceptual gotcha where one resource is an AR instance and another is a pure hash.

I'd probably make a scope and association to help out here:

    class Comment
      scope :with_vote_count, ->{ joins(:votes).select('comments.*').select('count(votes.*) as vote_count') }
    end

    class Post
      has_many :comments
      has_many :comments_with_vote_counts, ->{ with_vote_counts }, class_name: 'Comment'
    end

    # in controller
    @posts = Post.includes(:comments_with_vote_counts).limit(3).order(:created_at: :desc)

    # in view/serializer, posts and comments are both AR instances
    @posts.each do |post|
      post.comments.each do |comment|
        comment.vote_count # => Integer
      end
    end
This should give you 2 queries, one to load the posts, then one to load the comments and vote counts for the relevant posts. Controller stays nice and slim and the complexity is delegated to sql via the join scope, without any other dependencies.

* edited for HN code block syntax