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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With