【发布时间】:2012-11-26 02:05:33
【问题描述】:
这里最好的方法是什么?我正在尝试清理一些代码,我想知道控制器是否是这种逻辑的最佳位置:
if user_signed_in?
if current_user.try(:admin?)
@docs = Doc.chronologic.page(params[:page]).per(5)
@orders = Order.chronologic.page(params[:page]).per(5)
else
@docs = Doc.chronologic.where(:user_id => current_user.ftp, :retired => "active").page(params[:page]).per(5)
@orders = Order.chronologic.where(:user => current_user.ftp).page(params[:page]).per(5)
end
respond_to do |format|
format.html
format.json { render json: @docs }
end
else
redirect_to new_user_session_path
end
如果有更好的位置,它会在哪里?
谢谢!
编辑:对于像 pdf 这样的方法来说要糟糕得多,它对虾有一行又一行的说明,但我似乎无法让 send_data 从模型中工作。
【问题讨论】:
-
哪个
if困扰您?user_signed_in?一个还是admin?一个? -
我想你可以拥有
for_user范围,但在这样的简单案例中这是一个见仁见智的问题。user_signed_in?确实应该由before_filter处理。并且不需要current_user.try(:admin?),只需current_user.admin?就足够了,因为user_signed_in?检查应该避免current_user.nil?的情况,并且无论如何您都假设!current_user.nil?用于非管理员用户。 -
旁注:Ryan Bates 做了an excellent RailsCasts,它展示了一种使用 Prawn 生成 PDF 的好方法,并将代码置于控制器之外。
标签: ruby-on-rails-3 model-view-controller