Shortest way to query to db tables and append all appropriate id's into array?

Am I being overly verbose on doing this?


    @user = User.find(session[:user])
    @involved_list = @user.projects
    @leading_list = Project.is_leader(session[:user])
    
    @list = []
    @involved_list.each do |p| @list << p.id end 
    @leading_list.each do |p| @list << p.id end

Another improvement:

@involved_list = @user.projects.find(:all, :select => :id).collect {|p| p.id}

The :select => :id means that the SQL is select id from projects, rather than select * ( everything ) from projects when you only need the ID.

Also, if you’re feeling fancy you can change
.collect {|p| p.id}
to
.map(&:id)
which does the same thing. The &:id results in a call to Symbol#to_proc. :id is the symbol, and the to_proc results in {|p| p.id} - it’s just some syntax sugar.

MUCH better than what I had originally. Thanks!

I think you could potentially shorten it up to:


@user = User.find(session[:user])
  @involved_list = @user.projects.collect {|p| p.id}
  @leading_list = Project.is_leader(@user).collect {|p| p.id}

  @list = @involved_list + @leading_list


I figured I should probably explain my example a bit more.

The {|variable| code goes here} syntax is typically used for blocks when it all fits on one line, and the do end syntax for multiple line blocks.

The Array#collect method iterates through an array and generates a new array from the results of the block.

Array#+ method generates a new array that contains the elements from both arrays.

Hope this helps.