SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Guru downtroden's Avatar
    Join Date
    Dec 2004
    Location
    illinois
    Posts
    971
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

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

    Am I being overly verbose on doing this?

    Code Ruby:
        @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
    your brain reacts in the same way whether you are
    looking at something or thinking about it...

  2. #2
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Location
    Cleveland, OH
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think you could potentially shorten it up to:

    Code:
    @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

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Location
    Cleveland, OH
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  4. #4
    SitePoint Guru downtroden's Avatar
    Join Date
    Dec 2004
    Location
    illinois
    Posts
    971
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    MUCH better than what I had originally. Thanks!
    your brain reacts in the same way whether you are
    looking at something or thinking about it...

  5. #5
    SitePoint Member
    Join Date
    Jan 2001
    Location
    Dunedin, New Zealand
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •