Offer options if record already exists in Ruby on Rails











up vote
0
down vote

favorite












I'm creating a database of products and want to check when a new product is created, if that product already exists.



99% of the time, the product should have a unique product code, but sometimes this will not be the case when a revised version comes out with the same product code.



I would like to have it so that the database checks if the product code exists already. If it does, then the user can either go ahead and create the product anyway, go to the product that already exists, or cancel.



I am trying to achieve this in the controller but cannot seem to get the syntax of the exists? method correct. Can someone point out where I am going wrong, please?



def create
@product = Product.new(product_params)

if Product.product_code.exists?(@product.product_code)
render 'new'
flash[:error] = "This product already exists."

elsif @product.save
redirect_to @product
else
render 'new'
end

end









share|improve this question






















  • You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
    – arieljuod
    22 hours ago

















up vote
0
down vote

favorite












I'm creating a database of products and want to check when a new product is created, if that product already exists.



99% of the time, the product should have a unique product code, but sometimes this will not be the case when a revised version comes out with the same product code.



I would like to have it so that the database checks if the product code exists already. If it does, then the user can either go ahead and create the product anyway, go to the product that already exists, or cancel.



I am trying to achieve this in the controller but cannot seem to get the syntax of the exists? method correct. Can someone point out where I am going wrong, please?



def create
@product = Product.new(product_params)

if Product.product_code.exists?(@product.product_code)
render 'new'
flash[:error] = "This product already exists."

elsif @product.save
redirect_to @product
else
render 'new'
end

end









share|improve this question






















  • You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
    – arieljuod
    22 hours ago















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm creating a database of products and want to check when a new product is created, if that product already exists.



99% of the time, the product should have a unique product code, but sometimes this will not be the case when a revised version comes out with the same product code.



I would like to have it so that the database checks if the product code exists already. If it does, then the user can either go ahead and create the product anyway, go to the product that already exists, or cancel.



I am trying to achieve this in the controller but cannot seem to get the syntax of the exists? method correct. Can someone point out where I am going wrong, please?



def create
@product = Product.new(product_params)

if Product.product_code.exists?(@product.product_code)
render 'new'
flash[:error] = "This product already exists."

elsif @product.save
redirect_to @product
else
render 'new'
end

end









share|improve this question













I'm creating a database of products and want to check when a new product is created, if that product already exists.



99% of the time, the product should have a unique product code, but sometimes this will not be the case when a revised version comes out with the same product code.



I would like to have it so that the database checks if the product code exists already. If it does, then the user can either go ahead and create the product anyway, go to the product that already exists, or cancel.



I am trying to achieve this in the controller but cannot seem to get the syntax of the exists? method correct. Can someone point out where I am going wrong, please?



def create
@product = Product.new(product_params)

if Product.product_code.exists?(@product.product_code)
render 'new'
flash[:error] = "This product already exists."

elsif @product.save
redirect_to @product
else
render 'new'
end

end






ruby-on-rails ruby sqlite ruby-on-rails-5






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 23 hours ago









Emily

255




255












  • You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
    – arieljuod
    22 hours ago




















  • You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
    – arieljuod
    22 hours ago


















You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
– arieljuod
22 hours ago






You can use active record's validations (uniqueness validation) on the product_code field so @product won't save if the product_code is already in use and then you can check if @product.errors[:product_code] show the taken error.
– arieljuod
22 hours ago














2 Answers
2






active

oldest

votes

















up vote
-1
down vote



accepted










Instead if Product.product_code.exists?(@product.product_code) possibly you should use if @product.product_code.present?



UPD: thanks to all, commented below.



Correct use of exists? is Product.where(product_code: @product.product_code).exists?






share|improve this answer























  • I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
    – Emily
    23 hours ago












  • what error message it gives? Post it here.
    – igor_rb
    23 hours ago










  • undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
    – Emily
    23 hours ago










  • I updated my answer
    – igor_rb
    23 hours ago






  • 1




    Correct use of exists? is Product.where(product_code: @product.product_code).exists?
    – Dorian
    12 hours ago


















up vote
0
down vote













You should note that what you are doing in the controller or adding a standard uniqueness validation to the model will not allow duplicate Products to be created at all.



This will just keep sending the user back to the form:



def create
@product = Product.new(product_params)
if Product.exists?(product_code: @product.product_code)
render 'new'
flash[:error] = "This product already exists."
elsif @product.save
redirect_to @product
else
render 'new'
end
end


If you want to simply warn the user once you can attach a virtual attribute on the model and use it as condition for the validation:



class Product < ApplicationRecord
attribute :dup_warning, :boolean, default: true
validate :lax_product_code_uniquenes

def lax_product_code_uniqueness
if new_record? && !dup_warning && Product.exists(product_code: self.product_code)
errors.add(:product_code, 'is not unique - are you sure?')
self.dup_warning = true
end
end
end


Then add the virtual attribute to the form:



<%= form_with(model: @product) do |f| %>
...
<%= f.hidden_input(:dup_warning) %>
...
<% end %>


And you don't need to really do anything in the controller besides add dup_warning to the params whitelist.



def create
@product = Product.new(product_params)
if @product.save
redirect_to @product
else
render 'new'
end
end

def product_params
params.require(:product)
.permit(:foo, :bar, :product_code, :dup_warning)
end





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343720%2foffer-options-if-record-already-exists-in-ruby-on-rails%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    -1
    down vote



    accepted










    Instead if Product.product_code.exists?(@product.product_code) possibly you should use if @product.product_code.present?



    UPD: thanks to all, commented below.



    Correct use of exists? is Product.where(product_code: @product.product_code).exists?






    share|improve this answer























    • I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
      – Emily
      23 hours ago












    • what error message it gives? Post it here.
      – igor_rb
      23 hours ago










    • undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
      – Emily
      23 hours ago










    • I updated my answer
      – igor_rb
      23 hours ago






    • 1




      Correct use of exists? is Product.where(product_code: @product.product_code).exists?
      – Dorian
      12 hours ago















    up vote
    -1
    down vote



    accepted










    Instead if Product.product_code.exists?(@product.product_code) possibly you should use if @product.product_code.present?



    UPD: thanks to all, commented below.



    Correct use of exists? is Product.where(product_code: @product.product_code).exists?






    share|improve this answer























    • I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
      – Emily
      23 hours ago












    • what error message it gives? Post it here.
      – igor_rb
      23 hours ago










    • undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
      – Emily
      23 hours ago










    • I updated my answer
      – igor_rb
      23 hours ago






    • 1




      Correct use of exists? is Product.where(product_code: @product.product_code).exists?
      – Dorian
      12 hours ago













    up vote
    -1
    down vote



    accepted







    up vote
    -1
    down vote



    accepted






    Instead if Product.product_code.exists?(@product.product_code) possibly you should use if @product.product_code.present?



    UPD: thanks to all, commented below.



    Correct use of exists? is Product.where(product_code: @product.product_code).exists?






    share|improve this answer














    Instead if Product.product_code.exists?(@product.product_code) possibly you should use if @product.product_code.present?



    UPD: thanks to all, commented below.



    Correct use of exists? is Product.where(product_code: @product.product_code).exists?







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 11 hours ago

























    answered 23 hours ago









    igor_rb

    853624




    853624












    • I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
      – Emily
      23 hours ago












    • what error message it gives? Post it here.
      – igor_rb
      23 hours ago










    • undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
      – Emily
      23 hours ago










    • I updated my answer
      – igor_rb
      23 hours ago






    • 1




      Correct use of exists? is Product.where(product_code: @product.product_code).exists?
      – Dorian
      12 hours ago


















    • I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
      – Emily
      23 hours ago












    • what error message it gives? Post it here.
      – igor_rb
      23 hours ago










    • undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
      – Emily
      23 hours ago










    • I updated my answer
      – igor_rb
      23 hours ago






    • 1




      Correct use of exists? is Product.where(product_code: @product.product_code).exists?
      – Dorian
      12 hours ago
















    I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
    – Emily
    23 hours ago






    I tried that - unfortunately it gives an error: undefined method `exists?' for "1234":String
    – Emily
    23 hours ago














    what error message it gives? Post it here.
    – igor_rb
    23 hours ago




    what error message it gives? Post it here.
    – igor_rb
    23 hours ago












    undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
    – Emily
    23 hours ago




    undefined method `exists?' for "1234":String - 1234 is the product code I was trying out.
    – Emily
    23 hours ago












    I updated my answer
    – igor_rb
    23 hours ago




    I updated my answer
    – igor_rb
    23 hours ago




    1




    1




    Correct use of exists? is Product.where(product_code: @product.product_code).exists?
    – Dorian
    12 hours ago




    Correct use of exists? is Product.where(product_code: @product.product_code).exists?
    – Dorian
    12 hours ago












    up vote
    0
    down vote













    You should note that what you are doing in the controller or adding a standard uniqueness validation to the model will not allow duplicate Products to be created at all.



    This will just keep sending the user back to the form:



    def create
    @product = Product.new(product_params)
    if Product.exists?(product_code: @product.product_code)
    render 'new'
    flash[:error] = "This product already exists."
    elsif @product.save
    redirect_to @product
    else
    render 'new'
    end
    end


    If you want to simply warn the user once you can attach a virtual attribute on the model and use it as condition for the validation:



    class Product < ApplicationRecord
    attribute :dup_warning, :boolean, default: true
    validate :lax_product_code_uniquenes

    def lax_product_code_uniqueness
    if new_record? && !dup_warning && Product.exists(product_code: self.product_code)
    errors.add(:product_code, 'is not unique - are you sure?')
    self.dup_warning = true
    end
    end
    end


    Then add the virtual attribute to the form:



    <%= form_with(model: @product) do |f| %>
    ...
    <%= f.hidden_input(:dup_warning) %>
    ...
    <% end %>


    And you don't need to really do anything in the controller besides add dup_warning to the params whitelist.



    def create
    @product = Product.new(product_params)
    if @product.save
    redirect_to @product
    else
    render 'new'
    end
    end

    def product_params
    params.require(:product)
    .permit(:foo, :bar, :product_code, :dup_warning)
    end





    share|improve this answer

























      up vote
      0
      down vote













      You should note that what you are doing in the controller or adding a standard uniqueness validation to the model will not allow duplicate Products to be created at all.



      This will just keep sending the user back to the form:



      def create
      @product = Product.new(product_params)
      if Product.exists?(product_code: @product.product_code)
      render 'new'
      flash[:error] = "This product already exists."
      elsif @product.save
      redirect_to @product
      else
      render 'new'
      end
      end


      If you want to simply warn the user once you can attach a virtual attribute on the model and use it as condition for the validation:



      class Product < ApplicationRecord
      attribute :dup_warning, :boolean, default: true
      validate :lax_product_code_uniquenes

      def lax_product_code_uniqueness
      if new_record? && !dup_warning && Product.exists(product_code: self.product_code)
      errors.add(:product_code, 'is not unique - are you sure?')
      self.dup_warning = true
      end
      end
      end


      Then add the virtual attribute to the form:



      <%= form_with(model: @product) do |f| %>
      ...
      <%= f.hidden_input(:dup_warning) %>
      ...
      <% end %>


      And you don't need to really do anything in the controller besides add dup_warning to the params whitelist.



      def create
      @product = Product.new(product_params)
      if @product.save
      redirect_to @product
      else
      render 'new'
      end
      end

      def product_params
      params.require(:product)
      .permit(:foo, :bar, :product_code, :dup_warning)
      end





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You should note that what you are doing in the controller or adding a standard uniqueness validation to the model will not allow duplicate Products to be created at all.



        This will just keep sending the user back to the form:



        def create
        @product = Product.new(product_params)
        if Product.exists?(product_code: @product.product_code)
        render 'new'
        flash[:error] = "This product already exists."
        elsif @product.save
        redirect_to @product
        else
        render 'new'
        end
        end


        If you want to simply warn the user once you can attach a virtual attribute on the model and use it as condition for the validation:



        class Product < ApplicationRecord
        attribute :dup_warning, :boolean, default: true
        validate :lax_product_code_uniquenes

        def lax_product_code_uniqueness
        if new_record? && !dup_warning && Product.exists(product_code: self.product_code)
        errors.add(:product_code, 'is not unique - are you sure?')
        self.dup_warning = true
        end
        end
        end


        Then add the virtual attribute to the form:



        <%= form_with(model: @product) do |f| %>
        ...
        <%= f.hidden_input(:dup_warning) %>
        ...
        <% end %>


        And you don't need to really do anything in the controller besides add dup_warning to the params whitelist.



        def create
        @product = Product.new(product_params)
        if @product.save
        redirect_to @product
        else
        render 'new'
        end
        end

        def product_params
        params.require(:product)
        .permit(:foo, :bar, :product_code, :dup_warning)
        end





        share|improve this answer












        You should note that what you are doing in the controller or adding a standard uniqueness validation to the model will not allow duplicate Products to be created at all.



        This will just keep sending the user back to the form:



        def create
        @product = Product.new(product_params)
        if Product.exists?(product_code: @product.product_code)
        render 'new'
        flash[:error] = "This product already exists."
        elsif @product.save
        redirect_to @product
        else
        render 'new'
        end
        end


        If you want to simply warn the user once you can attach a virtual attribute on the model and use it as condition for the validation:



        class Product < ApplicationRecord
        attribute :dup_warning, :boolean, default: true
        validate :lax_product_code_uniquenes

        def lax_product_code_uniqueness
        if new_record? && !dup_warning && Product.exists(product_code: self.product_code)
        errors.add(:product_code, 'is not unique - are you sure?')
        self.dup_warning = true
        end
        end
        end


        Then add the virtual attribute to the form:



        <%= form_with(model: @product) do |f| %>
        ...
        <%= f.hidden_input(:dup_warning) %>
        ...
        <% end %>


        And you don't need to really do anything in the controller besides add dup_warning to the params whitelist.



        def create
        @product = Product.new(product_params)
        if @product.save
        redirect_to @product
        else
        render 'new'
        end
        end

        def product_params
        params.require(:product)
        .permit(:foo, :bar, :product_code, :dup_warning)
        end






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 17 hours ago









        max

        43.7k856103




        43.7k856103






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343720%2foffer-options-if-record-already-exists-in-ruby-on-rails%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy