Skip to content

Latest commit

 

History

History
201 lines (140 loc) · 4.05 KB

rails_questions.md

File metadata and controls

201 lines (140 loc) · 4.05 KB

Ruby on Rails Questions


These questions go with a Sample App that you can find here


1. Find all the posts commented by the first user
Tips

You can start with a joins.

Answer

Post.joins(:comments).where(:comments => {user: User.first})


2. Find out how many comments they are for each post, be careful for N+1 queries !
Tips

One includes a day keep the n + 1 query away.

Answer

Post.includes(:comments).map { |post| post.comments.size }


3. We want to display the first five posts on our main page, correct the method in the model Post
Tips

It's about setting boundaries.

Answer

  def self.first_five
    limit(5)
  end


4. Find out which users are born before 2010
Tips

StackOverFlow is strong with this one.

Answer

  User.where('extract(year from birthdate) < ?', 2010)


5. Write a method to dynamically find all users born before a given year
Tips

You need to write a scope, here is a tutorial.

Answer

    scope :born_before, ->(year) { where('extract(year from birthdate) < ?', year) }


6. Make sure that an user can only comment an article once
Tips

You need to write a validation.

Answer

     validates :user, uniqueness: { scope: :post,
    message: "can only comment once" }


7. Finds out all the posts without a comment
Tips

I don't really have a hint for that because it's kind of magic.

Answer

     Post.includes(:comments).where(comments: { post_id: nil })


8. Get in a array the content of the comments for the last post
Tips

Spoiler alert: it's a one-liner thanks to this.

Answer

     Post.last.comments.pluck(:content)


9. We want to make sure that every time a comment is made on a post, the post timestamps are updated
Tips

You'll need a callback and, I'm not kidding, this is an hint.

Answer

You'll have a after_save callback like this in comment:

    def update_post
      post.touch
    end