我如何在 rails 中遵循干法

How can I follow dry method in rails

我是 rails 的新手。所以不知道如何遵循DRY方法。让我们深入探讨这个问题。

我的控制器中有两个方法,它们都遵循相同的代码。那么我怎样才能减少我的代码。在这两种方法中,只有型号名称有所不同。请帮助我

我需要这样的东西

array = ['Userservice', 'Userschedule' ]
    array.each do |el|
        draft_info = el.find_by(user_id: 39, save_option: "publish")
        draft_info.delete if !draft_info.nil?
        @user_info = el.find_by(user_id: 39, save_option: "draft")
        el.create(@user_info.attributes.merge({:save_option => "publish", :id => el.maximum(:id).to_i.next }))
    end




def create_publish_user
    publish_user_schedule
    publish_user_service
end

def publish_user_service
 draft_service =  Userservice.where(user_id: current_user.id, save_option: "publish").delete_all
 user_service = Userservice.where(user_id: current_user.id, save_option: "draft")
 user_service.each { |ser|  
  Userservice.create(ser.attributes.merge({:save_option => "publish", :id => Userservice.maximum(:id).to_i.next }))
 }
end

def publish_user_schedule
 draft_schedule =  Userschedule.where(user_id: current_user.id, save_option: "publish").delete_all
 user_schedule = Userschedule.where(user_id: current_user.id, save_option: "draft")
 user_schedule.each { |sch|  
   Userschedule.create(sch.attributes.merge({:save_option => "publish", :id => Userschedule.maximum(:id).to_i.next }))
  }
end  

您可以将参数传递给您的方法

def publish(type)
  draft = type.where(....)
  data = type.where(....)
  data.each ....
  # And so on
end

# Somewhere in your code you use it then
publish(UserService)

看来您应该能够执行以下操作:

['Userservice', 'Userschedule'].each do |el|
  el_class = el.constantize
  if draft_info = el_class.find_by(user_id: 39, save_option: "publish")
    draft_info.delete
  end
  @user_info = el_class.find_by(user_id: 39, save_option: "draft")
  el_class.create(
    @user_info.attributes.merge({
      save_option: :publish, 
      id: el_class.maximum(:id).to_i.next 
    })
  )
end

我不知道你为什么在做 create 时指定 id。你为什么要这样做而不是让 ActiveRecord 为你处理?