我的代码当前工作正常,但我可以说它可以做得更好。所以我想我会要求一些意见。
对于给定的费用,用户可以提交或取消提交。这会在expense_approvals表中创建一条记录,并将approval_status设置为1或0。
当有人取消提交费用,然后重新提交费用时,复杂性就会出现,因为记录已经存在,我必须加入逻辑来处理它,以及一个非常难看的视图。
我的直觉告诉我,我可以在模型和/或控制器中做些事情,使其更加清洁。
所以我的模型看起来像这样:
class Expense < ActiveRecord::Base
attr_accessible :amount, :expense_date, :description
has_one :expense_approval
end
和
class ExpenseApproval < ActiveRecord::Base
attr_accessible :approval_date, :approval_status, :approver_id, :expense_id
belongs_to :expense, foreign_key: :expense_id
validates_uniqueness_of :expense_id
end
和控制器
def submit_expense
@expense_list = Expense.all
expense = Expense.find(params[:id])
if expense.expense_approval
approval = ExpenseApproval.find(expense.expense_approval.id)
approval.approval_status = 1
else
approval = ExpenseApproval.new(approval_status: "1", expense_id: expense.id)
end
if approval.save
#flash[:success] = "You have added an submission."
redirect_to expense_approvals_path
else
flash[:error] = "Error"
redirect_to expense_approvals_path
end
end
def un_submit_expense
@expense_list = Expense.all
@expense = ExpenseApproval.find(params[:id])
@expense.approval_status = 0
if @expense.save
#flash[:success] = "You have un submitted."
redirect_to expense_approvals_path
else
flash[:error] = "Unsubmit Error"
redirect_to expense_approvals_path
end
end
并查看
<% if expense_item.expense_approval %>
<%#=expense_item.expense_approval.approval_status%>
<% if expense_item.expense_approval.approval_status == 1 %>
<%= link_to raw('<i class="icon-arrow-down icon-white"> </i>'),
un_submit_expense_path(expense_item.expense_approval[:id]),
class: "btn btn-mini btn-warning",
:confirm => "Are you sure you want to un submit this expense?" %>
<% end %>
<% if expense_item.expense_approval.approval_status == 0 %>
<%= link_to raw('<i class="icon-arrow-up icon-white"> </i>'),
submit_expense_path(expense_item[:id]),
class: "btn btn-mini btn-info",
:confirm => "Are you sure you want to submit this expense?" %>
<% end %>
<% else %>
<%= link_to raw('<i class="icon-arrow-up icon-white"> </i>'),
submit_expense_path(expense_item[:id]),
class: "btn btn-mini btn-info",
:confirm => "Are you sure you want to submit this expense?" %>
<% end %>
答案 0 :(得分:1)
您可以使用decorator清理视图。
此外,您还有一些代码重复,例如:
if @expense.save
flash[:success] = "You have un submitted."
redirect_to expense_approvals_path
else
flash[:error] = "Unsubmit Error"
redirect_to expense_approvals_path
end
几乎与:
相同if @expense.save
flash[:success] = "You have un submitted."
else
flash[:error] = "Unsubmit Error"
end
redirect_to expense_approvals_path