【问题标题】:Checking if form.date_select from form exists in PostgreSQL data field. Ruby on Rails 6检查表单中的 form.date_select 是否存在于 PostgreSQL 数据字段中。 Ruby on Rails 6
【发布时间】:2026-02-06 04:40:01
【问题描述】:

我有一个带有 date_select 的表单。

<%= form_for @post, url: { controller: "posts", action: "create" } do |form| %>
<%= form.date_select :date %>


我正在尝试根据 post.date 和 post.user_id 字段检查我的 post_controller.rb 是否存在以下行

@existing_post = Post.where(user_id: current_user.id, date: params[:post][:date].to_s).first


if @existing_post.present?
  @existing_post.body += "<hr>#{params[:post][:body]}"
  @existing_post.save(post_params)
else
  @post = Post.new(post_params)
end

如果帖子存在,我想使用 += 附加,如果帖子不存在,我想创建新的。但 params[:post][:date].to_s 不返回任何数据。它看起来 NIL。我错过了什么?

后加载(1.8 毫秒)选择“posts”。 FROM “posts”,其中“posts”。“user_id” = $1 AND “posts”。“date”为 NULL ORDER BY "posts"."id" ASC LIMIT $2 [["user_id", 1], ["LIMIT", 1]]*

【问题讨论】:

    标签: ruby-on-rails postgresql forms date


    【解决方案1】:

    好的解决了。

    显然我应该格式化日期。

    # date(1i)"=>"2021", "date(2i)"=>"3", "date(3i)"=>"22"
    @selected_date = Date.new(params["post"]["date(1i)"].to_i,
                              params["post"]["date(2i)"].to_i,
                              params["post"]["date(3i)"].to_i)
    

    【讨论】:

      【解决方案2】:

      您可以通过将参数分配给模型实例来使用 Rails 内置的多参数分配:

      date = Post.new(params.fetch(:post).permit(:date)).date
      
      @existing_post = Post.where(user_id: current_user.id, date: date).first
      
      if @existing_post.present?
        # you should probally use strftime instead of implicit casting
        @existing_post.body += "<hr>#{date.to_s}" 
        @existing_post.save(post_params)
      else
        @post = Post.new(post_params)
      end
      

      【讨论】: