我的代码当前工作得很好,但我可以说它可以做得更好。所以我想我会要求一些意见。
对于给定的费用,用户可以提交或取消提交。这会在费用审批表中创建一条记录,并将审批状态设置为 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 %>