0
votes

I got problem in validation with modal popup. This is my index.html.haml:

.container-index
  %h1 All Posts Here
  %button.btn.btn-info(type="button" data-toggle="modal" data-target="#myModal") New Post

  = render 'form'
  - @posts.each do |post|
    .col-md-4
      %h3= link_to post.title,post
      %p= post.content
      = "#{time_ago_in_words post.created_at} ago "

_form.html.haml:

.container
  = simple_form_for current_user.posts.build do |f|
    %div.modal.fade#myModal(tabindex="-1" role="dialog" aria-labelledby="myModalLabel")
      %div.modal-dialog(role="document")
        %div.modal-content
          %div.modal-header
            %button.close(type="button" data-dismiss="modal" aria-label="Close")
              %span(aria-hidden="true") ×
            %h3.modal-title#myModalLabel New Post

          %div.modal-body
            = f.input :title, label:"Title",class:'form-group',name: 'title'
            = f.input :content, label:'Content',class:'form-group',name:'content'

          %div.modal-footer
            %button.btn.btn-danger#mynewpostclose(type="button" data-dismiss="modal") Close
            = f.submit 'Create', class:"btn btn-primary"

post.rb:

validates :title, presence: true
validates :content, presence: true

posts_controller.rb:

 
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

  def index
    @posts = Post.all.order("created_at DESC")
  end

  def new
    @post = current_user.posts.build
  end

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to @post, notice: 'Created Successfully'
    else
      render 'new'
    end

  end

  def show
  end

  def edit

  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Updated Successfully'
    else
      render 'edit'
    end
  end

  def destroy
    @post.destroy
    redirect_to posts_path(@post), notice: 'Deleted Successfully'
  end

  private

  def find_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :content)
  end

I do not know how to show up the warning
When I create a new post without any title or content
it'll link to a blank page and don't create any new post
I just wanna call warning inside modal when submit, anyone can help me,plzz?

1
I think you should use JavaScript in simple_form_for .... remote: true and in JS you will be able add errorsOleg Sobchuk
Will you clearly more a litle bit,plzz? I'd never use this way beforeryudo617

1 Answers

0
votes

In your form you need to replace this line

= simple_form_for current_user.posts.build do |f|

with this;

= simple_form_for @post do |f|

This way, when your create action renders the new template, the form will be given the instance of Post which failed to save allowing simple form to display the error messages.