所以,我做到了!我不知道这是否正确,但我干燥了这段代码。
两个控制器:
posts_controller.rb
def init_comments
if Post.comments_manipulator(current_user, params[:post_ids] ||= []) > 0
@posts = Post.new_post_to_follow
code = []
@posts.each do |post|
group = post.group
code = code_constructor('API.call')
end
Post.comments_init(get_request(code), @posts)
end
redirect_to :back
end
boards_controller.rb
def init_comments
if Board.comments_manipulator(current_user, params[:board_ids] ||= []) > 0
@boards = Board.new_board_to_follow
code = []
@boards.each do |board|# подготовка запроса
group = board.group
code = code_constructor('API.call')
end
Board.comments_init(get_request(code), @boards)
end
redirect_to :back
end
正如你所看到的,它们是完全一样的。在模型board.rb
和post.rb
-include CommentsInitializer
而在models\concerns
module CommentsInitializer
extend ActiveSupport::Concern
module ClassMethods
def comments_manipulator(user, ids)
relationship = self.name.downcase + 's'
a = user.send(relationship).pluck(:id)
b = ids.map(&:to_i)
follow = b - a
unfollow = a - b
follow.each do |id| # start to follow newly checked obj
@obj = self.find_by_id(id)
if @obj.users.empty?
@obj.update_attribute(:new_follow, true)
end
user.send(relationship) << @obj
end
unfollow.each do |id| # remove from following
@obj = self.find_by_id(id)
remove_assoc_from_user(@obj, user)#destroy relation with current user
end
follow.size
end
def comments_init(comments, objs)
i = 0
objs.each do |obj| # updating comments data
if comments[i]['count'] == 0
obj.update(new_follow: false)
else
obj.update(new_follow: false, last_comment_id: comments[i]['items'][0]['id'])
end
i += 1
end
end
def remove_assoc_from_user(obj, user)
user = user.id
if user
obj.users.delete(user)
end
end
end
我的代码有效。如果您知道如何使它更好,请回答!