Offer options if record already exists in Ruby on Rails





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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
    Nov 16 '18 at 19:12




















0















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
    Nov 16 '18 at 19:12
















0












0








0








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 Nov 16 '18 at 18:47









EmilyEmily

327




327













  • 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
    Nov 16 '18 at 19:12





















  • 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
    Nov 16 '18 at 19:12



















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
Nov 16 '18 at 19:12







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
Nov 16 '18 at 19:12














2 Answers
2






active

oldest

votes


















-1














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
    Nov 16 '18 at 18:59













  • what error message it gives? Post it here.

    – igor_rb
    Nov 16 '18 at 19:00











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

    – Emily
    Nov 16 '18 at 19:04











  • I updated my answer

    – igor_rb
    Nov 16 '18 at 19:06






  • 1





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

    – Dorian
    Nov 17 '18 at 5:21



















0














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',
    autoActivateHeartbeat: false,
    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









    -1














    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
      Nov 16 '18 at 18:59













    • what error message it gives? Post it here.

      – igor_rb
      Nov 16 '18 at 19:00











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

      – Emily
      Nov 16 '18 at 19:04











    • I updated my answer

      – igor_rb
      Nov 16 '18 at 19:06






    • 1





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

      – Dorian
      Nov 17 '18 at 5:21
















    -1














    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
      Nov 16 '18 at 18:59













    • what error message it gives? Post it here.

      – igor_rb
      Nov 16 '18 at 19:00











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

      – Emily
      Nov 16 '18 at 19:04











    • I updated my answer

      – igor_rb
      Nov 16 '18 at 19:06






    • 1





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

      – Dorian
      Nov 17 '18 at 5:21














    -1












    -1








    -1







    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 Nov 17 '18 at 6:37

























    answered Nov 16 '18 at 18:57









    igor_rbigor_rb

    933627




    933627













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

      – Emily
      Nov 16 '18 at 18:59













    • what error message it gives? Post it here.

      – igor_rb
      Nov 16 '18 at 19:00











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

      – Emily
      Nov 16 '18 at 19:04











    • I updated my answer

      – igor_rb
      Nov 16 '18 at 19:06






    • 1





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

      – Dorian
      Nov 17 '18 at 5:21



















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

      – Emily
      Nov 16 '18 at 18:59













    • what error message it gives? Post it here.

      – igor_rb
      Nov 16 '18 at 19:00











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

      – Emily
      Nov 16 '18 at 19:04











    • I updated my answer

      – igor_rb
      Nov 16 '18 at 19:06






    • 1





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

      – Dorian
      Nov 17 '18 at 5:21

















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

    – Emily
    Nov 16 '18 at 18:59







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

    – Emily
    Nov 16 '18 at 18:59















    what error message it gives? Post it here.

    – igor_rb
    Nov 16 '18 at 19:00





    what error message it gives? Post it here.

    – igor_rb
    Nov 16 '18 at 19:00













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

    – Emily
    Nov 16 '18 at 19:04





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

    – Emily
    Nov 16 '18 at 19:04













    I updated my answer

    – igor_rb
    Nov 16 '18 at 19:06





    I updated my answer

    – igor_rb
    Nov 16 '18 at 19:06




    1




    1





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

    – Dorian
    Nov 17 '18 at 5:21





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

    – Dorian
    Nov 17 '18 at 5:21













    0














    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




























      0














      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


























        0












        0








        0







        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 Nov 17 '18 at 0:26









        maxmax

        46.9k1060106




        46.9k1060106






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            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

            The Sandy Post

            Danny Elfman

            Pages that link to "Head v. Amoskeag Manufacturing Co."