Quoting arwed <[email protected]>:
> 
> This works, but I am sure there is a better way todo this:
> 
>   # GET /posts/1/edit
>   def edit
>     @post = Post.find(params[:id])
>     # Find user galleries that have not been used in posts yet
>     usergalleries = Array.new
>     @post.user.galleries.each do |pug|
>       usergalleries << pug.id
>     end
>     userpostgalleries = Array.new
>     @post.user.posts.each do |pup|
>       userpostgalleries << pup.gallery_id
>     end
>     aug = usergalleries - userpostgalleries
>     @availableusergalleries = @post.user.galleries.find
> (:all, :conditions => { :id => aug })
>   end
> 
> Any ideas?
> 

#     @post = Post.find(params[:id])
     @post = Post.find(params[:id], :include => {:user => [:galleries, :posts]})

# One database call instead of many.  I think this is correct form, but 
# have no easy way to test it.

#     # Find user galleries that have not been used in posts yet
#     usergalleries = Array.new
#     @post.user.galleries.each do |pug|
#       usergalleries << pug.id
#     end
     user_galleries = @post.user.galleries.map{|pug| pug[:id]}

# I find pug[:id] more reliable than pug.id; the latter in some contexts is
# interpreted as the Object id, instead of the primary key/ID from the
# database and a deprecation warning is given.

#     userpostgalleries = Array.new
#     @post.user.posts.each do |pup|
#       userpostgalleries << pup.gallery_id
#     end
     user_post_galleries = @post.user.posts.map{|pup| pup.gallery_id}

     aug = usergalleries - userpostgalleries
#     @availableusergalleries = @post.user.galleries.find(:all, :conditions =>
{ :id => aug })
     @availableusergalleries = @post.user.galleries.find(aug)

# ActiveRecord.find will take an array of IDs.


Another way that takes less memory (if speed is of more concern, benchmark
both):

    aug = @post.user.galleries.map{|pug| pug[:id]}
    @post.user.posts.each{|pup| aug.delete(pup.gallery_id)}

    @availableusergalleries = Gallery.find(aug)


HTH,
  Jeffrey

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to