Form fields are not displaying when error occurs in rails












-1












$begingroup$


I have used Ajax call for creating Post. It displays form correctly when click button create post.it not shows fields when i only upload image without field values. i don't know how it happens. when all fields are empty it shows validation error perfectly.like this,enter image description here



when i upload image without filling the field it ignores the field like this,enter image description here



and this is my posts_controller



    class PostsController < ApplicationController
before_action :set_topic
before_action :set_post, except: [:create, :new, :index]

def index
if params[:topic_id].to_i > 0
@posts = @topic.posts.all
else
@posts = Post.includes(:topic).references(:topic).all
@posts = @posts.order('topic desc')
end
@posts = @posts.eager_load(:ratings, :comments, :user, :users).paginate(page: params[:page], per_page: 10)
@tags = Tag.all
end

def show
@comment = @post.comments.new
end

def mark_as_read
@post.users << current_user unless @post.users.include?(current_user)
end

def new
@post = @topic.posts.new
@tags = Tag.all
end

def create
@post = @topic.posts.new(post_params)
@post.user_id = current_user.id
@posts = @topic.posts.paginate(page: params[:page], per_page: 10).eager_load(:user, :users, :comments, :ratings)
respond_to do |format|
if @post.save
format.js {render 'posts/create'}
elsif @post.image.save
format.js {render 'posts/new'}
else
format.js {render 'posts/new'}
end
end
end

def edit
authorize! :edit, @post
@tags = Tag.all
end

def update
params[:post][:tag_ids] ||=
if @post.update(post_params)
redirect_to topic_post_path(@topic, @post), notice: 'Post was successfully updated.'
else
render :edit
end
end

def destroy
authorize! :destroy, @post
if @post.destroy
redirect_to topic_posts_path(@topic), notice: 'Post was successfully destroyed.'
else
render 'posts/show'
end
end

private

def set_topic
if params[:topic_id].present?
@topic = Topic.find(params[:topic_id])
end
end

def set_post
@post = @topic.posts.find(params[:id])
end

def post_params
params.require(:post).permit(:name, :description, :image, :topic_id, {tag_ids: }, :tags_attributes => [:name])
end
end


And this is my _form.html.erb



    <%= form_for [@topic, @post], multipart: true, remote: true, authenticity_token: true do |form| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this topic from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :name, placeholder: "Enter Post name", class: "form-control" %><br/>
<%= form.text_area :description, placeholder: "Enter Description", class: "form-control" %><br/>
<%= form.file_field :image, class: "form-control-file" %><br/>
<h3><strong>Select Tag</strong></h3>
<% @tags = Tag.all %>
<% if @tags %>
<% @tags.each do |tag| %>
<div>
<%= check_box_tag "post[tag_ids]", tag.id, @post.tags.include?(tag) %>
<%= tag.name %>
</div>
<% end %>
<% end %>
<%= form.fields_for :tags, @post.tags.build do |f| %>
<%= f.text_field :name, placeholder: "Add Custom Tag" %>
<% end %>
<%= form.submit class: "btn btn-primary", data: {"disable-with": "Saving..."} %>
<% end %>


and this is my new.js.erb



$('#new-link').html("<%= j (render 'form') %>");
<% if @post.errors.any? %>
alert("ERROR(S): <%= @post.errors.full_messages.join(',').html_safe %>")
<% end %>


and this is my create.js.erb



$('#new-link').hide();
alert("Post Created Successfully");


and this is the button i have used for render form



<div class="card-body">
<h5 class="card-title"><%= @topic.topic %></h5>
<div id="new-link">
<div id='ajax_loader' style="display: none;">
<%= image_tag '/assets/loader.gif' %>
</div>
<script>
$(document).ajaxStop(function () {
$("#ajax_loader").hide();
});
$(document).ajaxStart(function () {
$("#ajax_loader").show();
});
</script>
<%= link_to 'create Post', new_topic_post_path(@topic), class: "btn btn-primary", remote: true, data: {"disable-with": "Please wait..."} %>
</div>
</div>









share|improve this question







New contributor




RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    -1












    $begingroup$


    I have used Ajax call for creating Post. It displays form correctly when click button create post.it not shows fields when i only upload image without field values. i don't know how it happens. when all fields are empty it shows validation error perfectly.like this,enter image description here



    when i upload image without filling the field it ignores the field like this,enter image description here



    and this is my posts_controller



        class PostsController < ApplicationController
    before_action :set_topic
    before_action :set_post, except: [:create, :new, :index]

    def index
    if params[:topic_id].to_i > 0
    @posts = @topic.posts.all
    else
    @posts = Post.includes(:topic).references(:topic).all
    @posts = @posts.order('topic desc')
    end
    @posts = @posts.eager_load(:ratings, :comments, :user, :users).paginate(page: params[:page], per_page: 10)
    @tags = Tag.all
    end

    def show
    @comment = @post.comments.new
    end

    def mark_as_read
    @post.users << current_user unless @post.users.include?(current_user)
    end

    def new
    @post = @topic.posts.new
    @tags = Tag.all
    end

    def create
    @post = @topic.posts.new(post_params)
    @post.user_id = current_user.id
    @posts = @topic.posts.paginate(page: params[:page], per_page: 10).eager_load(:user, :users, :comments, :ratings)
    respond_to do |format|
    if @post.save
    format.js {render 'posts/create'}
    elsif @post.image.save
    format.js {render 'posts/new'}
    else
    format.js {render 'posts/new'}
    end
    end
    end

    def edit
    authorize! :edit, @post
    @tags = Tag.all
    end

    def update
    params[:post][:tag_ids] ||=
    if @post.update(post_params)
    redirect_to topic_post_path(@topic, @post), notice: 'Post was successfully updated.'
    else
    render :edit
    end
    end

    def destroy
    authorize! :destroy, @post
    if @post.destroy
    redirect_to topic_posts_path(@topic), notice: 'Post was successfully destroyed.'
    else
    render 'posts/show'
    end
    end

    private

    def set_topic
    if params[:topic_id].present?
    @topic = Topic.find(params[:topic_id])
    end
    end

    def set_post
    @post = @topic.posts.find(params[:id])
    end

    def post_params
    params.require(:post).permit(:name, :description, :image, :topic_id, {tag_ids: }, :tags_attributes => [:name])
    end
    end


    And this is my _form.html.erb



        <%= form_for [@topic, @post], multipart: true, remote: true, authenticity_token: true do |form| %>
    <% if @post.errors.any? %>
    <div id="error_explanation">
    <h2><%= pluralize(@post.errors.count, "error") %> prohibited this topic from being saved:</h2>
    <ul>
    <% @post.errors.full_messages.each do |message| %>
    <li><%= message %></li>
    <% end %>
    </ul>
    </div>
    <% end %>
    <%= form.text_field :name, placeholder: "Enter Post name", class: "form-control" %><br/>
    <%= form.text_area :description, placeholder: "Enter Description", class: "form-control" %><br/>
    <%= form.file_field :image, class: "form-control-file" %><br/>
    <h3><strong>Select Tag</strong></h3>
    <% @tags = Tag.all %>
    <% if @tags %>
    <% @tags.each do |tag| %>
    <div>
    <%= check_box_tag "post[tag_ids]", tag.id, @post.tags.include?(tag) %>
    <%= tag.name %>
    </div>
    <% end %>
    <% end %>
    <%= form.fields_for :tags, @post.tags.build do |f| %>
    <%= f.text_field :name, placeholder: "Add Custom Tag" %>
    <% end %>
    <%= form.submit class: "btn btn-primary", data: {"disable-with": "Saving..."} %>
    <% end %>


    and this is my new.js.erb



    $('#new-link').html("<%= j (render 'form') %>");
    <% if @post.errors.any? %>
    alert("ERROR(S): <%= @post.errors.full_messages.join(',').html_safe %>")
    <% end %>


    and this is my create.js.erb



    $('#new-link').hide();
    alert("Post Created Successfully");


    and this is the button i have used for render form



    <div class="card-body">
    <h5 class="card-title"><%= @topic.topic %></h5>
    <div id="new-link">
    <div id='ajax_loader' style="display: none;">
    <%= image_tag '/assets/loader.gif' %>
    </div>
    <script>
    $(document).ajaxStop(function () {
    $("#ajax_loader").hide();
    });
    $(document).ajaxStart(function () {
    $("#ajax_loader").show();
    });
    </script>
    <%= link_to 'create Post', new_topic_post_path(@topic), class: "btn btn-primary", remote: true, data: {"disable-with": "Please wait..."} %>
    </div>
    </div>









    share|improve this question







    New contributor




    RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      -1












      -1








      -1





      $begingroup$


      I have used Ajax call for creating Post. It displays form correctly when click button create post.it not shows fields when i only upload image without field values. i don't know how it happens. when all fields are empty it shows validation error perfectly.like this,enter image description here



      when i upload image without filling the field it ignores the field like this,enter image description here



      and this is my posts_controller



          class PostsController < ApplicationController
      before_action :set_topic
      before_action :set_post, except: [:create, :new, :index]

      def index
      if params[:topic_id].to_i > 0
      @posts = @topic.posts.all
      else
      @posts = Post.includes(:topic).references(:topic).all
      @posts = @posts.order('topic desc')
      end
      @posts = @posts.eager_load(:ratings, :comments, :user, :users).paginate(page: params[:page], per_page: 10)
      @tags = Tag.all
      end

      def show
      @comment = @post.comments.new
      end

      def mark_as_read
      @post.users << current_user unless @post.users.include?(current_user)
      end

      def new
      @post = @topic.posts.new
      @tags = Tag.all
      end

      def create
      @post = @topic.posts.new(post_params)
      @post.user_id = current_user.id
      @posts = @topic.posts.paginate(page: params[:page], per_page: 10).eager_load(:user, :users, :comments, :ratings)
      respond_to do |format|
      if @post.save
      format.js {render 'posts/create'}
      elsif @post.image.save
      format.js {render 'posts/new'}
      else
      format.js {render 'posts/new'}
      end
      end
      end

      def edit
      authorize! :edit, @post
      @tags = Tag.all
      end

      def update
      params[:post][:tag_ids] ||=
      if @post.update(post_params)
      redirect_to topic_post_path(@topic, @post), notice: 'Post was successfully updated.'
      else
      render :edit
      end
      end

      def destroy
      authorize! :destroy, @post
      if @post.destroy
      redirect_to topic_posts_path(@topic), notice: 'Post was successfully destroyed.'
      else
      render 'posts/show'
      end
      end

      private

      def set_topic
      if params[:topic_id].present?
      @topic = Topic.find(params[:topic_id])
      end
      end

      def set_post
      @post = @topic.posts.find(params[:id])
      end

      def post_params
      params.require(:post).permit(:name, :description, :image, :topic_id, {tag_ids: }, :tags_attributes => [:name])
      end
      end


      And this is my _form.html.erb



          <%= form_for [@topic, @post], multipart: true, remote: true, authenticity_token: true do |form| %>
      <% if @post.errors.any? %>
      <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this topic from being saved:</h2>
      <ul>
      <% @post.errors.full_messages.each do |message| %>
      <li><%= message %></li>
      <% end %>
      </ul>
      </div>
      <% end %>
      <%= form.text_field :name, placeholder: "Enter Post name", class: "form-control" %><br/>
      <%= form.text_area :description, placeholder: "Enter Description", class: "form-control" %><br/>
      <%= form.file_field :image, class: "form-control-file" %><br/>
      <h3><strong>Select Tag</strong></h3>
      <% @tags = Tag.all %>
      <% if @tags %>
      <% @tags.each do |tag| %>
      <div>
      <%= check_box_tag "post[tag_ids]", tag.id, @post.tags.include?(tag) %>
      <%= tag.name %>
      </div>
      <% end %>
      <% end %>
      <%= form.fields_for :tags, @post.tags.build do |f| %>
      <%= f.text_field :name, placeholder: "Add Custom Tag" %>
      <% end %>
      <%= form.submit class: "btn btn-primary", data: {"disable-with": "Saving..."} %>
      <% end %>


      and this is my new.js.erb



      $('#new-link').html("<%= j (render 'form') %>");
      <% if @post.errors.any? %>
      alert("ERROR(S): <%= @post.errors.full_messages.join(',').html_safe %>")
      <% end %>


      and this is my create.js.erb



      $('#new-link').hide();
      alert("Post Created Successfully");


      and this is the button i have used for render form



      <div class="card-body">
      <h5 class="card-title"><%= @topic.topic %></h5>
      <div id="new-link">
      <div id='ajax_loader' style="display: none;">
      <%= image_tag '/assets/loader.gif' %>
      </div>
      <script>
      $(document).ajaxStop(function () {
      $("#ajax_loader").hide();
      });
      $(document).ajaxStart(function () {
      $("#ajax_loader").show();
      });
      </script>
      <%= link_to 'create Post', new_topic_post_path(@topic), class: "btn btn-primary", remote: true, data: {"disable-with": "Please wait..."} %>
      </div>
      </div>









      share|improve this question







      New contributor




      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I have used Ajax call for creating Post. It displays form correctly when click button create post.it not shows fields when i only upload image without field values. i don't know how it happens. when all fields are empty it shows validation error perfectly.like this,enter image description here



      when i upload image without filling the field it ignores the field like this,enter image description here



      and this is my posts_controller



          class PostsController < ApplicationController
      before_action :set_topic
      before_action :set_post, except: [:create, :new, :index]

      def index
      if params[:topic_id].to_i > 0
      @posts = @topic.posts.all
      else
      @posts = Post.includes(:topic).references(:topic).all
      @posts = @posts.order('topic desc')
      end
      @posts = @posts.eager_load(:ratings, :comments, :user, :users).paginate(page: params[:page], per_page: 10)
      @tags = Tag.all
      end

      def show
      @comment = @post.comments.new
      end

      def mark_as_read
      @post.users << current_user unless @post.users.include?(current_user)
      end

      def new
      @post = @topic.posts.new
      @tags = Tag.all
      end

      def create
      @post = @topic.posts.new(post_params)
      @post.user_id = current_user.id
      @posts = @topic.posts.paginate(page: params[:page], per_page: 10).eager_load(:user, :users, :comments, :ratings)
      respond_to do |format|
      if @post.save
      format.js {render 'posts/create'}
      elsif @post.image.save
      format.js {render 'posts/new'}
      else
      format.js {render 'posts/new'}
      end
      end
      end

      def edit
      authorize! :edit, @post
      @tags = Tag.all
      end

      def update
      params[:post][:tag_ids] ||=
      if @post.update(post_params)
      redirect_to topic_post_path(@topic, @post), notice: 'Post was successfully updated.'
      else
      render :edit
      end
      end

      def destroy
      authorize! :destroy, @post
      if @post.destroy
      redirect_to topic_posts_path(@topic), notice: 'Post was successfully destroyed.'
      else
      render 'posts/show'
      end
      end

      private

      def set_topic
      if params[:topic_id].present?
      @topic = Topic.find(params[:topic_id])
      end
      end

      def set_post
      @post = @topic.posts.find(params[:id])
      end

      def post_params
      params.require(:post).permit(:name, :description, :image, :topic_id, {tag_ids: }, :tags_attributes => [:name])
      end
      end


      And this is my _form.html.erb



          <%= form_for [@topic, @post], multipart: true, remote: true, authenticity_token: true do |form| %>
      <% if @post.errors.any? %>
      <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this topic from being saved:</h2>
      <ul>
      <% @post.errors.full_messages.each do |message| %>
      <li><%= message %></li>
      <% end %>
      </ul>
      </div>
      <% end %>
      <%= form.text_field :name, placeholder: "Enter Post name", class: "form-control" %><br/>
      <%= form.text_area :description, placeholder: "Enter Description", class: "form-control" %><br/>
      <%= form.file_field :image, class: "form-control-file" %><br/>
      <h3><strong>Select Tag</strong></h3>
      <% @tags = Tag.all %>
      <% if @tags %>
      <% @tags.each do |tag| %>
      <div>
      <%= check_box_tag "post[tag_ids]", tag.id, @post.tags.include?(tag) %>
      <%= tag.name %>
      </div>
      <% end %>
      <% end %>
      <%= form.fields_for :tags, @post.tags.build do |f| %>
      <%= f.text_field :name, placeholder: "Add Custom Tag" %>
      <% end %>
      <%= form.submit class: "btn btn-primary", data: {"disable-with": "Saving..."} %>
      <% end %>


      and this is my new.js.erb



      $('#new-link').html("<%= j (render 'form') %>");
      <% if @post.errors.any? %>
      alert("ERROR(S): <%= @post.errors.full_messages.join(',').html_safe %>")
      <% end %>


      and this is my create.js.erb



      $('#new-link').hide();
      alert("Post Created Successfully");


      and this is the button i have used for render form



      <div class="card-body">
      <h5 class="card-title"><%= @topic.topic %></h5>
      <div id="new-link">
      <div id='ajax_loader' style="display: none;">
      <%= image_tag '/assets/loader.gif' %>
      </div>
      <script>
      $(document).ajaxStop(function () {
      $("#ajax_loader").hide();
      });
      $(document).ajaxStart(function () {
      $("#ajax_loader").show();
      });
      </script>
      <%= link_to 'create Post', new_topic_post_path(@topic), class: "btn btn-primary", remote: true, data: {"disable-with": "Please wait..."} %>
      </div>
      </div>






      ruby-on-rails ajax twitter-bootstrap






      share|improve this question







      New contributor




      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 12 mins ago









      RAJKUMAR PALANISAMYRAJKUMAR PALANISAMY

      1




      1




      New contributor




      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      RAJKUMAR PALANISAMY is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          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: "196"
          };
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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
          });


          }
          });






          RAJKUMAR PALANISAMY is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214093%2fform-fields-are-not-displaying-when-error-occurs-in-rails%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          RAJKUMAR PALANISAMY is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          RAJKUMAR PALANISAMY is a new contributor. Be nice, and check out our Code of Conduct.













          RAJKUMAR PALANISAMY is a new contributor. Be nice, and check out our Code of Conduct.












          RAJKUMAR PALANISAMY is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • 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.


          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f214093%2fform-fields-are-not-displaying-when-error-occurs-in-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

          Costa Masnaga

          Fotorealismo

          Create new schema in PostgreSQL using DBeaver