Rails 3.我认为这应该更容易

时间:2013-07-06 05:51:56

标签: ruby-on-rails-3 dry

我尝试学习RoR并拥有以下代码。我只觉得它可以轻松多了。我从RoR那里得知的是,你应该尽量不重复,尽可能地让事情变得简单。所以也许有人对此有一些建议:

    if params[:select_date].present?
  if params[:select_date] == '1'
    params[:search][:date_started_at_gte] = Date.today.beginning_of_month
  end
  if params[:select_date] == '2'
    params[:search][:date_started_at_gte] = Date.today - 1.months
  end
  if params[:select_date] == '3'
    params[:search][:date_started_at_gte] = Date.today - 3.months
  end
  if params[:select_date] == '0'
    params[:search][:date_started_at_gte] = params[:search][:date_started_at_gte]
    params[:search][:date_started_at_lte] = params[:search][:date_started_at_lte]
  end
else
    params[:search][:date_started_at_gte] = Date.today.beginning_of_month
    params[:search][:date_started_at_lte] = Date.today
end

谢谢!

1 个答案:

答案 0 :(得分:0)

gte = lte = ''

case params[:select_date]
when '1'
  gte = Date.today.beginning_of_month
when '2'
  gte = Date.today - 1.months
#...
when '0'
  gte = params[:search][:date_started_at_gte]
  lte = params[:search][:date_started_at_lte]
else
  gte = Date.today.beginning_of_month
  lte = Date.today
end

我在这里使用了一些新变量gte, lte。我强烈建议你不要改变参数的值!