如果具有相同属性的记录存在,则更改创建的行为

时间:2019-01-25 20:49:57

标签: ruby-on-rails ruby validation activerecord

我正在构建一个类似reddit的应用程序,您可以在其中将提交内容添加到特定的用户页面提交具有一些属性,包括名为 url 的属性。 我想在添加新提交时检查该特定页面是否已经存在具有相同url的提交,如果存在,请对其投票,而不是将其创建为新提交。如果没有,只需将其添加为新提交。我在这里使用 act_as_votable 宝石。

这是创建方法:

def create
    @user = User.friendly.find(params[:user_id])
    @submission =  @user.submissions.new(submission_params)
    @submission.member_id = current_user.id
    @submission.creator_id = @user.id
    @submission.is_viewed = false
    @submission.get_thumb_and_title_by_url(@submission.url)
    respond_to do |format|
       if @submission.save

        format.html { redirect_to @user, notice: 'Submission was 
 successfully created.' }
        format.json { render :show, status: :created, location: @submission }
       else
           format.html { render :new }
           format.json { render json: @user.errors, status: :unprocessable_entity }
       end
     end
  end

1 个答案:

答案 0 :(得分:0)

您应该看看https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_byhttps://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_initialize_by

现在在您的代码上,我们可以进行

之类的更改
def create
    @user = User.friendly.find(params[:user_id]) 
    @submission =  @user.submissions.find_or_initialize_by(submission_params)
    if @submission.id.present? 
      # What to do if the record exists 
    else
      # if its a new record 
      @submission.member_id = current_user.id
      @submission.creator_id = @user.id
      @submission.is_viewed = false
      @submission.get_thumb_and_title_by_url(@submission.url)
    end


    respond_to do |format|
       if @submission.save

        format.html { redirect_to @user, notice: 'Submission was 
 successfully created.' }
        format.json { render :show, status: :created, location: @submission }
       else
           format.html { render :new }
           format.json { render json: @user.errors, status: :unprocessable_entity }
       end
     end
  end

我希望这可以使您走上正轨

快乐编码