重构rails控制器代码

时间:2016-11-23 07:52:19

标签: ruby-on-rails ruby refactoring

我想减少Rails项目中的重复代码。

def update_receipt
  user = current_user
  Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i)
  Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i, tax_number: params[:tax_number].to_i) if params[:receipt_type].to_i == 2 
end

有没有更好的方法来重构上述代码?

1 个答案:

答案 0 :(得分:0)

更新回答:

def update_receipt
  attrs = params.slice(:phone_number, :address, :receipt_type)
  attrs[:tax_number] = params[:tax_number] if attrs[:receipt_type].to_i == 2
  Receipt.update(user.receipt.id, attrs)
end