Ruby on Rails 5 - Resource gives error when checking if it already exists - whether it does or not





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







0















I am trying to check whether a product already exists or not - if it does, a flash message should appear, with a link to the product that already exists. If not, the product should be created.



The problem is that the flash error is appearing whether the product already exists or not. Where am I going wrong?



products_controller.rb:



def create
@product = Product.new(product_params)

if @product.product_code.present?
@existing_product = Product.where(product_code: "#{@product.product_code}").ids.first.to_s
flash.now[:error] = %Q[This product already exists: <a href="/products/#{@existing_product}">#{@product.product_code}</a>. Please either rename this product or view/edit the existing one.].html_safe
render 'new'

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

end


If I try and use the exists? method (rather than present?), I get the following error:



undefined method `exists?' for "1234":String


1234 is the product code I am trying.










share|improve this question





























    0















    I am trying to check whether a product already exists or not - if it does, a flash message should appear, with a link to the product that already exists. If not, the product should be created.



    The problem is that the flash error is appearing whether the product already exists or not. Where am I going wrong?



    products_controller.rb:



    def create
    @product = Product.new(product_params)

    if @product.product_code.present?
    @existing_product = Product.where(product_code: "#{@product.product_code}").ids.first.to_s
    flash.now[:error] = %Q[This product already exists: <a href="/products/#{@existing_product}">#{@product.product_code}</a>. Please either rename this product or view/edit the existing one.].html_safe
    render 'new'

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

    end


    If I try and use the exists? method (rather than present?), I get the following error:



    undefined method `exists?' for "1234":String


    1234 is the product code I am trying.










    share|improve this question

























      0












      0








      0








      I am trying to check whether a product already exists or not - if it does, a flash message should appear, with a link to the product that already exists. If not, the product should be created.



      The problem is that the flash error is appearing whether the product already exists or not. Where am I going wrong?



      products_controller.rb:



      def create
      @product = Product.new(product_params)

      if @product.product_code.present?
      @existing_product = Product.where(product_code: "#{@product.product_code}").ids.first.to_s
      flash.now[:error] = %Q[This product already exists: <a href="/products/#{@existing_product}">#{@product.product_code}</a>. Please either rename this product or view/edit the existing one.].html_safe
      render 'new'

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

      end


      If I try and use the exists? method (rather than present?), I get the following error:



      undefined method `exists?' for "1234":String


      1234 is the product code I am trying.










      share|improve this question














      I am trying to check whether a product already exists or not - if it does, a flash message should appear, with a link to the product that already exists. If not, the product should be created.



      The problem is that the flash error is appearing whether the product already exists or not. Where am I going wrong?



      products_controller.rb:



      def create
      @product = Product.new(product_params)

      if @product.product_code.present?
      @existing_product = Product.where(product_code: "#{@product.product_code}").ids.first.to_s
      flash.now[:error] = %Q[This product already exists: <a href="/products/#{@existing_product}">#{@product.product_code}</a>. Please either rename this product or view/edit the existing one.].html_safe
      render 'new'

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

      end


      If I try and use the exists? method (rather than present?), I get the following error:



      undefined method `exists?' for "1234":String


      1234 is the product code I am trying.







      ruby-on-rails ruby 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 20:38









      EmilyEmily

      327




      327
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Your conditional is checking the wrong thing. This:



          if @product.product_code.present?


          only checks if product_code is present in the @product you just made, it does't check if there's anything already in the database with that product code.



          I think you want something more like this:



          @existing_product = Product.find_by(product_code: @product.product_code)
          if @existing_product
          flash.now[:error] = ...
          render 'new'
          elsif @product.save
          redirect_to @product
          else
          render 'new'
          end


          You can use find_by to find the thing you're looking for, that will either give you the product or nil if there isn't a matching product.



          You might want to look into a couple other things:




          1. Using the URL helper rather than manually building a link would be better.

          2. Your model should be checking the uniqueness of the product codes rather than the controller.

          3. As Dorian mentions in the comments, HTML in the flash messages isn't the best idea. You'd be better off checking @existing_product in the view and then putting up the link and whatever "complex" error message you need entirely within the view.






          share|improve this answer


























          • Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

            – Emily
            Nov 16 '18 at 21:25






          • 1





            You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

            – Dorian
            Nov 17 '18 at 5:09






          • 1





            @Dorian Good point, I added that the "other things" list.

            – mu is too short
            Nov 17 '18 at 8:25












          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%2f53345061%2fruby-on-rails-5-resource-gives-error-when-checking-if-it-already-exists-whet%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Your conditional is checking the wrong thing. This:



          if @product.product_code.present?


          only checks if product_code is present in the @product you just made, it does't check if there's anything already in the database with that product code.



          I think you want something more like this:



          @existing_product = Product.find_by(product_code: @product.product_code)
          if @existing_product
          flash.now[:error] = ...
          render 'new'
          elsif @product.save
          redirect_to @product
          else
          render 'new'
          end


          You can use find_by to find the thing you're looking for, that will either give you the product or nil if there isn't a matching product.



          You might want to look into a couple other things:




          1. Using the URL helper rather than manually building a link would be better.

          2. Your model should be checking the uniqueness of the product codes rather than the controller.

          3. As Dorian mentions in the comments, HTML in the flash messages isn't the best idea. You'd be better off checking @existing_product in the view and then putting up the link and whatever "complex" error message you need entirely within the view.






          share|improve this answer


























          • Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

            – Emily
            Nov 16 '18 at 21:25






          • 1





            You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

            – Dorian
            Nov 17 '18 at 5:09






          • 1





            @Dorian Good point, I added that the "other things" list.

            – mu is too short
            Nov 17 '18 at 8:25
















          2














          Your conditional is checking the wrong thing. This:



          if @product.product_code.present?


          only checks if product_code is present in the @product you just made, it does't check if there's anything already in the database with that product code.



          I think you want something more like this:



          @existing_product = Product.find_by(product_code: @product.product_code)
          if @existing_product
          flash.now[:error] = ...
          render 'new'
          elsif @product.save
          redirect_to @product
          else
          render 'new'
          end


          You can use find_by to find the thing you're looking for, that will either give you the product or nil if there isn't a matching product.



          You might want to look into a couple other things:




          1. Using the URL helper rather than manually building a link would be better.

          2. Your model should be checking the uniqueness of the product codes rather than the controller.

          3. As Dorian mentions in the comments, HTML in the flash messages isn't the best idea. You'd be better off checking @existing_product in the view and then putting up the link and whatever "complex" error message you need entirely within the view.






          share|improve this answer


























          • Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

            – Emily
            Nov 16 '18 at 21:25






          • 1





            You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

            – Dorian
            Nov 17 '18 at 5:09






          • 1





            @Dorian Good point, I added that the "other things" list.

            – mu is too short
            Nov 17 '18 at 8:25














          2












          2








          2







          Your conditional is checking the wrong thing. This:



          if @product.product_code.present?


          only checks if product_code is present in the @product you just made, it does't check if there's anything already in the database with that product code.



          I think you want something more like this:



          @existing_product = Product.find_by(product_code: @product.product_code)
          if @existing_product
          flash.now[:error] = ...
          render 'new'
          elsif @product.save
          redirect_to @product
          else
          render 'new'
          end


          You can use find_by to find the thing you're looking for, that will either give you the product or nil if there isn't a matching product.



          You might want to look into a couple other things:




          1. Using the URL helper rather than manually building a link would be better.

          2. Your model should be checking the uniqueness of the product codes rather than the controller.

          3. As Dorian mentions in the comments, HTML in the flash messages isn't the best idea. You'd be better off checking @existing_product in the view and then putting up the link and whatever "complex" error message you need entirely within the view.






          share|improve this answer















          Your conditional is checking the wrong thing. This:



          if @product.product_code.present?


          only checks if product_code is present in the @product you just made, it does't check if there's anything already in the database with that product code.



          I think you want something more like this:



          @existing_product = Product.find_by(product_code: @product.product_code)
          if @existing_product
          flash.now[:error] = ...
          render 'new'
          elsif @product.save
          redirect_to @product
          else
          render 'new'
          end


          You can use find_by to find the thing you're looking for, that will either give you the product or nil if there isn't a matching product.



          You might want to look into a couple other things:




          1. Using the URL helper rather than manually building a link would be better.

          2. Your model should be checking the uniqueness of the product codes rather than the controller.

          3. As Dorian mentions in the comments, HTML in the flash messages isn't the best idea. You'd be better off checking @existing_product in the view and then putting up the link and whatever "complex" error message you need entirely within the view.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 17 '18 at 8:25

























          answered Nov 16 '18 at 21:16









          mu is too shortmu is too short

          355k58702677




          355k58702677













          • Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

            – Emily
            Nov 16 '18 at 21:25






          • 1





            You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

            – Dorian
            Nov 17 '18 at 5:09






          • 1





            @Dorian Good point, I added that the "other things" list.

            – mu is too short
            Nov 17 '18 at 8:25



















          • Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

            – Emily
            Nov 16 '18 at 21:25






          • 1





            You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

            – Dorian
            Nov 17 '18 at 5:09






          • 1





            @Dorian Good point, I added that the "other things" list.

            – mu is too short
            Nov 17 '18 at 8:25

















          Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

          – Emily
          Nov 16 '18 at 21:25





          Thanks very much, that works great. I just had to make sure the link was pointing to the id of the existing product, but otherwise worked great. Have been trying to use URL helpers but can't get it to escape the html. Will keep trying!

          – Emily
          Nov 16 '18 at 21:25




          1




          1





          You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

          – Dorian
          Nov 17 '18 at 5:09





          You shouldn't put HTML in your flash messages, better use a instance variable and use that in your view, e.g. using @existing_product if this case

          – Dorian
          Nov 17 '18 at 5:09




          1




          1





          @Dorian Good point, I added that the "other things" list.

          – mu is too short
          Nov 17 '18 at 8:25





          @Dorian Good point, I added that the "other things" list.

          – mu is too short
          Nov 17 '18 at 8:25




















          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%2f53345061%2fruby-on-rails-5-resource-gives-error-when-checking-if-it-already-exists-whet%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

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python