开发者

How can I execute my code better?

I have these two pieces of code, and I think they are ugly. How can I change them?

1

do_withs = Dowith.where(:friend_id => current_user.id)
@doweets = do_withs.collect { |f| f.doweet_id }
@doweets = @doweets.collect { |f| Doweet.find((F)) }
@doweets = @doweets + current_user.doweets 
@doweets.flatten!
@doweets.sort! { |a,b| a.date <=> b.date }

2

@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = @friendships.collect { |f| User.find(f.user_id) }
@friends_doweets = @friends.collect(&:doweets)
@doweets = @current_user_doweets  + @friends_doweets
@doweets.flatten!
@doweets.sort! { |a,b| b.created_at <=> a.created_at }

models:

class Doweet < ActiveRecord::Base
  has_many :comments
  has_many :likes
  has_many :dowiths
  belongs_to :user
end

class Dowith < ActiveRecord::Base
  belongs_to :doweet
end

class User < ActiveRecord::Base
  has_many :doweets
  has_many :friendships
end

class Friendship < ActiveRecord开发者_运维知识库::Base
  belongs_to :user  
end


this simplifies things a tad (but my syntax might be off...

@doweets = Dowith.where(:friend_id => current_user.id).collect do |d|
[
    Doweet.find(d.doweet_id)    
]
end

@doweets << current_user.doweets
@doweets.sort! do |a,b| a.date <=> b.date end


1) Take advantage of your model associations to reduce the number of database queries you generate by eager-loading with the includes method:

@doweets = Dowith.where(:friend_id => current_user.id).includes(:doweet).collect(&:doweet) + current_user.doweets
@doweets.sort! {|doweet1, doweet2| doweet1.date <=> doweet2.date}

2) Very similar to 1:

@friends_doweets = Friendship.where(:friend_id => current_user.id, :status => true).includes(:user => :doweets).collect{|friendship| friendship.user.doweets}
@doweets = current_user.doweets.limit(10) + @friends_doweets
@doweets.sort! { |a,b| b.created_at <=> a.created_at }

Watch your log file to see the difference in the number of database queries that occur. It's not a huge deal, but I think you can eliminate a lot of instance variables from your code and replace them with local variables. Instance variables in your controller actions should be used to pass data to your views.


@doweets = Dowith.where(:friend_id => current_user.id).collect &:doweet_id
@doweets = Doweet.find_all_by_id(@doweets)
@doweets = (@doweets + current_user.doweets).sort_by &:date


@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = User.includes(:doweets).find_all_by_id(@friendships.collect(&:user_id))
@friends_doweets = @friends.collect(&:doweets).flatten
@doweets = (@current_user_doweets + @friends_doweets).sort_by &:created_at
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜