Question: Rails: How to show items only if creator is unique?


Rails: How to show items only if creator is unique?

Answers 2
Added at 2016-12-28 13:12

I have many users and each user has multiple projects.

Now, I want to get only one item per user.

@projects = Project.all.where(user_id is unique)

That is project should be fetched only if no other project from the same user was fetched already.

Hope I was clear with my question. I am on Rails 5.


I am using postgres in production.

Answers to

Rails: How to show items only if creator is unique?

nr: #1 dodano: 2016-12-28 13:12

You probably would like to do something like this.


nr: #2 dodano: 2016-12-28 16:12

There are many ways in which you can do that. I would recommend the following code as a starting point:

projects_scope = Project.where(:status => "Published")
@projects = projects_scope.where(id:

Here's how it works:

  1. We'll use the scope of published projects twice so we assign it to a variable to make it more readable.
  2. We group projects by user_id and use maximum to pick the one with the highest ID (you could use minimum or any othe rmethod of picking one row from the group). In more detail:

    a. returns a Hash mapping user IDs to project IDs. For example { 12 => 17, 14 => 3 } means for user 12 we choose project 17 and for user 14 we choose project 3. b. We're interested only in project IDs so we get the values in the hash by calling Hash#values).

  3. Knowing the IDs, we query the database for the corresponding projects and assign the result to @projects.

If you'd like to learn some more advanced techniques I recommend you take a look this Stack Overflow question.

Source Show
◀ Wstecz