2016-01-21 196 views
0

我在模態彈出窗口驗證中遇到問題。這是我的index.html.haml關於軌道驗證4

 
.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 

我不知道如何顯示警告
當我創建一個沒有任何標題或內容的新帖子
它會鏈接到一個空白頁面並且不會創建任何新帖子
我只是想在提交時調用內部模態警告,任何人可以幫助我嗎?

+0

我認爲你應該在'simple_form_for .... remote:true'中使用JavaScript,並且在JS中你將能夠添加錯誤 –

+0

你會明白嗎?我不會在 – ryudo617

回答

0

在表單需要更換此行

= simple_form_for current_user.posts.build do |f| 

本;

= simple_form_for @post do |f| 

這樣,當你創建動作呈現new模板,表單將給出未能挽救允許簡單的形式來顯示錯誤消息後的實例。

+0

之前使用這種方式,但是它會顯示一個錯誤:「nil:NilClass」的未定義方法'model_name'。任何建議對我來說? – ryudo617

+0

你的new.html.haml視圖是什麼樣的? – tpbowden

+0

=的link_to「家」,root_path,等級:「BTN BTN-信息」 %H1新話題 =渲染「形式」 我不知道如何寫評論像你 – ryudo617