我是 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
看起来你应该能够做这样的事情:
['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
为你照顾呢?
您可以将参数传递给您的方法
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)