gpt4 book ai didi

ruby-on-rails - 我怎样才能更好地执行我的代码?

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:00 26 4
gpt4 key购买 nike

我有这两段代码,我觉得它们很丑。我该如何更改它们?

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 }

模型:

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

最佳答案

这稍微简化了一些事情(但我的语法可能不对...

@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

关于ruby-on-rails - 我怎样才能更好地执行我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6582553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com