代码之家  ›  专栏  ›  技术社区  ›  lastone

使用Ajax发布时,如何检查数据库中是否已经存在记录?

  •  0
  • lastone  · 技术社区  · 7 年前

    使用Ajax发布时,如何检查数据库中是否已经存在记录?

    这是我的Ajax代码:

        $.ajax({
            type: "POST",
            url: "team_selections#create",
            data: {
                team_selection: {
                    season_id: "1",
                    club_id: "1",
                    player_id: id,
                    fixture_week: "1",
                    position: pos
                }
            },
            dataType: "html"
        })
    

    这是我的Rails控制器代码:

        def create
            if !TeamSelection.where(season_id: params[:season_id], club_id: params[:club_id], player_id: params[:player_id], fixture_week: params[:fixture_week], position: params[:position]).exists?
            TeamSelection.create(selection_params)
            end
        end
    
    
    private
      def selection_params
        params.require(:team_selection).permit(:season_id, :club_id, :player_id, :fixture_week, :position)
      end
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   jvillian    7 年前

    您可以在控制器中使用find_或create_by rails方法。这将查找具有给定属性的第一条记录,或者如果找不到具有这些属性的记录,则创建一条记录。此方法始终返回一条记录,但如果尝试创建但由于验证错误而失败,则不会持久化该记录,您将获得在这种情况下Create返回的内容。

    def create
      TeamSelection.find_or_create_by(selection_params)
    end
    
        2
  •  0
  •   Jagdeep Singh    7 年前

    您可以在 before_action .

    before_action :check_record_exists?
    
    def create
      TeamSelection.create(selection_params)
      render_something
    end
    
    private
    
    def check_record_exists?
      if TeamSelection.where(selection_params.slice(:season_id, :club_id, :player_id, :fixture_week, :position)).exists?
        render json: { error: 'Record already exists' }
      end
    end
    
    def selection_params
      params.require(:team_selection).permit(:season_id, :club_id, :player_id, :fixture_week, :position)
    end
    

    注: 您肯定需要对模型进行验证,以防止创建此类记录。不要仅仅依赖控制器或JS中的签入。

        3
  •  0
  •   Imran    7 年前

    正如@jagdeep正确评论的那样:如果不希望多次创建类似记录,请在模型中添加验证。 但是这里的控制器没有返回任何响应,比如“记录已经存在” 替换您的 create 方法

    def create
        is_record_present = TeamSelection.where(season_id: params[:season_id], club_id: params[:club_id], player_id: params[:player_id], fixture_week: params[:fixture_week], position: params[:position]).exists?
      if !is_record_present
        TeamSelection.create(selection_params)
      else
        #return respose for example
        render json: {message: 'Record already present'}, status: :bad_request
      end
    end