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

Question

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

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

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.

EDIT:

I am using postgres in production.

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

You probably would like to do something like this.

Users.uniq.pluck(:projects)

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: projects_scope.group(:user_id).maximum(:id).values)

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. projects_scope.group(:user_id).maximum(:id) 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