2016-09-26 77 views
0

我试图呈现从模型验证产生的错误信息,但我结束了这个错误:Rails的:无法呈现的错误信息

First argument in form cannot contain nil or be empty

希望用有所帮助提供的代码...当我使用:注释而不是@comment时,我至少能够加载页面,但之后我不知道如何渲染错误部分,因为它是一个符号而不是实际的对象。现在,我已经将它更改为对象的实例变量,我收到了错误。

错误消息部分

<% if object.errors.any? %> 
    <div id="error_explanation"> 
    <div class="alert alert-danger"> 
     The form contains <%= pluralize(object.errors.count, "error") %> 
    </div> 
    <ul> 
     <% object.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
    </ul> 
    </div> 
<% end %> 

注释形式

<%= form_for @comment, url: comments_path do |f| %> 
    <%= render 'shared/error_messages', object: f.object %> 
    <%= f.hidden_field :user_id, value: current_user.id %> 
    <%= f.hidden_field :post_id, value: post.id %> 
    <%= f.text_area :content, size: "60x2", placeholder: "Comment on this post..." %> 
    <%= f.submit "Comment" %> 

邮政形式

<%= form_for [@user, @post] do |f| %> 
    <%= render 'shared/error_messages', object: f.object %> 
    <%= f.text_area :content, size: "60x12", placeholder: "What do you want to say?" %> 
    <%= f.submit "Post" %> 
<% end %>  

class CommentsController < ApplicationController 
    def index 
    @comments = Comment.all 
    end 

    def new 
    @comment = Comment.new 
    @user = User.find(params[:user_id]) 
    end 

    def create 
    @user = current_user 
    #@post = Post.find(params[:post_id]) 
    @comment = @user.comments.build(comment_params) 

    if @comment.save 
     flash[:success] = "Comment Posted!" 
     redirect_back(fallback_location: root_path) 
    else 
     flash[:notice] = "Could not post comment" 
     redirect_back(fallback_location: root_path) 
    end 
    end 


    private 

    def comment_params 
    params.require(:comment).permit(:content, :user_id, :post_id) 
    end 
end 

class PostsController < ApplicationController 

    def index 
    @posts = Post.all 
    @user = User.find(params[:user_id]) 
    end 

    def new 
    @post = Post.new 
    @user = User.find(params[:user_id]) 
    end 

    def create 
    @post = current_user.posts.build(post_params) 
    if @post.save 
     flash[:success] = "Posted!" 
     redirect_to user_path(current_user) 
    else 
     flash[:notice] = "Post could not be submitted" 
     redirect_to users_path 
    end 
    end 

    private 

    def post_params 
    params.require(:post).permit(:content) 
    end 
end 
+0

'object:f.object?'这是不正确的,我相信。尝试改变它的评论:'object:@ comment',post:'object:@ post' – mrvncaragay

+0

我可以通过在posts#index action中声明一个@comment变量来获取它,因为这是视图呈现的地方从 –

回答

0

我能够在我的职位的声明@comment变量#index动作得到它,因为这是该视图正在从渲染