使用Rails Simple Calendar筛选日事件遇语法错误,求优化方案
问题解决与优化方案
核心问题分析
- SQL语法错误:原代码直接在字符串SQL中写
date变量,数据库会将其识别为字段名而非Ruby变量,引发语法错误;同时未使用参数绑定,存在SQL注入风险。 - 日期比较逻辑不严谨:原条件无法准确筛选出与目标日期重叠的事件(比如跨天事件、完全在当天内的事件)。
修正后的控制器代码
def index # 安全解析日期参数,避免解析异常 target_date = params[:datefilter]&.to_date # 保留原有的月周范围查询逻辑 @scheduleevents = Scheduleevent.where( start_time: Time.current.beginning_of_month.beginning_of_week..Time.current.end_of_month.end_of_week ) # 筛选与目标日期重叠的事件 if target_date.present? day_start = target_date.beginning_of_day day_end = target_date.end_of_day # 使用参数绑定避免SQL注入,同时修正比较逻辑 @scheduleeventsday = @scheduleevents.where( "start_time < ? AND end_time > ?", day_end, day_start ) end end
按钮代码优化
用Rails原生的link_to替代内联onclick,更符合Rails开发规范,也更易维护:
<%= link_to day.strftime('%Y-%m-%d'), scheduleevents_path(datefilter: day), class: 'calendar-day-button' %>
如果必须使用<button>标签,可使用button_to:
<%= button_to day.strftime('%Y-%m-%d'), scheduleevents_path(datefilter: day), method: :get, class: 'calendar-day-button' %>
逻辑说明
- 参数绑定:通过
?占位符传递Ruby变量,Rails会自动处理数据库参数绑定,既解决语法错误又防范SQL注入。 - 重叠事件筛选:判断事件的
start_time早于目标日期结束时间、end_time晚于目标日期开始时间,确保所有和目标日期有交集的事件都能被筛选出来(包括跨天事件、当天内的事件)。
内容的提问来源于stack exchange,提问作者spacerobot
相关产品推荐
相关产品推荐

