我在视图中创建了一个日期范围表单,允许用户输入日期范围并在该特定范围内显示他们的报告。首先填写报告中的test_field_tags
,其中包含报告的.first.created_at
和.last.created_at
值。现在我正在尝试正确连接控制器,以便用户可以指定日期范围,但它不适合我。感谢帮助...
index.html.erb
<%= form_tag({:action => "index"}, {:class => "form-inline"}) do %>
<div class="form-group">
<%= text_field_tag(:start_date, @reports.first.created_at, class: "form-control", name: "startdate") %>
<p class="text-center">to</span>
<%= text_field_tag(:end_date, @reports.last.created_at, class: "form-control", name: "enddate") %>
</div>
<%= submit_tag "Update", class: "update-button" %>
<% end %>
reports_controller.rb
def index
@company = current_user.company
@locations = if @company
current_user.company_locations.order(:name)
else
[]
end
@reports = if @company
@company.reports.where(created_at: params[:start_date]..params[:end_date]).order("created_at DESC").paginate(page: params[:page], :per_page => 30)
else
[]
end
render 'reports/index.html.erb'
end
private
def report_params
params.permit(:start_date, :end_date)
end
我现在遇到的问题是我的text_field_tag
的占位符值未插入,因为我在控制器中的语句依赖于params[:start_date]
和params[:end_date]
值
最好的方法是做我想要完成的事情......这是预先填写我在DB中的整个范围,但是然后允许用户指定他们自己的范围并重新加载页面以产生这些结果?
答案 0 :(得分:0)
请尝试以下编辑:
(注意:开始日期和结束日期也会包含时间组件;如果您只对日期感兴趣,请将其更改为@reports.first.created_at.to_date.to_s
和@reports.last.created_at.to_date.to_s
。但是,它会是均匀的更清洁以使用Rails I18n
库。)
<%= form_tag({:action => "index"}, {:class => "form-inline"}) do %>
<div class="form-group">
<%= text_field_tag(:start_date, ((@reports.nil? || @reports.empty?) ? '' : @reports.first.created_at.to_s), class: "form-control", name: "startdate") %>
<p class="text-center">to</span>
<%= text_field_tag(:end_date, ((@reports.nil? || @reports.empty?) ? '' : @reports.last.created_at.to_s), class: "form-control", name: "enddate") %>
</div>
<%= submit_tag "Update", class: "update-button" %>
<% end %>
&#13;
在控制器中,您需要在加载表单时正确填充@reports
变量(GET操作),然后在提交表单时更新相同的变量(POST操作):
(注意:在定义日期范围时不要忘记括号)
def index
@company = current_user.company
unless @company.nil? || @company.reports.empty?
if request.post?
@reports = @company.reports.where(created_at: (params[:start_date]..params[:end_date])).order(created_at: :desc).paginate(page: params[:page], :per_page => 30)
else
@reports = @company.reports.order(created_at: :desc).paginate(page: params[:page], :per_page => 30)
end
end
render 'reports/index.html.erb'
end
&#13;
编辑:出于路由目的,您的/config/routes.rb应包含以下内容:
get 'reports/index' => "reports#index", as: :reports_index
post 'reports/index' => "reports#index"
然后您可以将表单标签声明编辑为以下内容:
<%= form_tag reports_index_path, method: :post, class: "form-inline" do %>
只需从控制器中的render
操作中删除index
行即可。最后,确保您的控制器名称与您的views子目录名称一致。如果index.html.erb
位于views/reports
内,那么您的控制器名称应为ReportsController
,控制器文件应为reports_controller.rb
。如果它是单数,请相应地修改我的答案。