获取未定义的方法'parent'

时间:2016-02-25 09:32:59

标签: html ruby-on-rails

所以我之前回答过这个问题,但我似乎仍然无法做到这一点。我试图让我的评论模型为主题和帖子做出评论。我只是希望评论控制器能够处理发布或主题的评论。

路线:

resources :topics, :posts do
     resources :comments, only: [:create, :destroy]
  end

主题模型:

  has_many :comments, dependent: :destroy

评论模型:

  belongs_to :post
  belongs_to :topic

发布:

  has_many :comments, dependent: :destroy

评论控制器:

def create

    if params[:post_id]
      @parent = Post.find(params[:post_id])
      @comment = @parent.comments.new(comment_params)
      @comment.user = current_user

      if @comment.save
        flash[:notice] = "Comment saved successfully."
        redirect_to [@parent.topic, @parent]
      else
        flash[:alert] = "Comment failed to save."
        redirect_to [@parent.topic, @parent]
      end
    elsif params[:topic_id]
      @parent = Topic.find(params[:topic_id])
      @comment = @parent.comments.new(comment_params)
      @comment.user = current_user

      if @comment.save
        flash[:notice] = "Comment saved successfully."
      else
        flash[:alert] = "Comment failed to save."
      end
    end
  end

  def comment_params
    params.require(:comment).permit(:body)
  end

comment / form.html

<%= form_for [@parent, @comment] do |f| %>
  <div class="form-group">
    <%= f.label :body, class: 'sr-only' %>
    <%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %>
  </div>
  <%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %>
<% end %>

我在尝试转到我的主题/节目视图时不断获得undefined local variable or method parent 我如何实现评论以显示主题/帖子视图

1 个答案:

答案 0 :(得分:0)

  

未定义的局部变量或方法父

您需要将本地变量parent&amp; comment)更改为实例变量@parent&amp; { {1}})在控制器操作中以及在视图中,以便在视图中使用它们。

以下应该有效

@comment

我也注意到有两个<%= form_for [@parent, @comment] do |f| %> <div class="form-group"> <%= f.label :body, class: 'sr-only' %> <%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %> </div> <%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %> <% end %> &amp;控制器操作中定义的@parent个变量。如果它是一个错字然后纠正它。