未定义的方法`每个' for nil:从另一个控制器调用NilClass

时间:2015-05-05 08:18:32

标签: methods controller undefined each

我试图触发群组/节目视图中的所有帖子,但我收到错误"未定义的方法`每个'为零:NilClass"。有人可以帮帮我吗?

~~对不起我的错误编码行为

posts_controller:

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

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

  def new
    @post = Post.new
  end

  def create
    post = Post.create(permitted_params)
    redirect_to post
  end

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

  def update
    post = Post.find(params[:id])
    post.update permitted_params
    redirect_to post
  end

  def destroy
    Post.destroy(params[:id])
    redirect_to posts_path
  end

  def permitted_params
    params.require(:post).permit(:message)
  end

end

groups_controller:

class GroupsController < ApplicationController

  def index
  end

  def show
    @group = Group.find(params[:id])
  end


  def new
    @group = Group.new
  end

  def create
    group = Group.create(permitted_params)
    redirect_to group
  end

    def permitted_params
      params.require(:group).permit(:name)
  end

end

基团/ show.html.erb:

<div class="container">
<p><i><%= @post.message %></i><p>

  <%= render 'posts/each' %>

  <% if user_signed_in? %>
  <p><%= link_to "Powrót", root_path %></p>
  <p><%= link_to "Usuń wiadomość", @post, method: :delete, data: { confirm: 'Jesteś pewien?' } %></p>
  <% end %>
</div>

_each.html.erb:

  <% @posts.each do |post| %>
    <ul><i><%= link_to post.message, post %></i></ul></br>
  <% end %>

路线:

devise_for :users

  root 'posts#index'

  resources :posts
  resources :groups

  get 'posts/each' => 'posts#each'
  get 'posts/group1' => 'posts#group1'

2 个答案:

答案 0 :(得分:0)

in groups_controller.rb

def show
  @group = Group.find(params[:id])
  @posts = Post.where(group_id: @group_id)
end

in groups / show.html.erb

<div class="container">

  <%= render 'posts/each', {posts: @posts} %>

  <% if user_signed_in? %>
    <p><%= link_to "Powrót", root_path %></p>
    <p><%= link_to "Usuń wiadomość", @post, method: :delete, data: { confirm:'Jesteś pewien?' } %></p>
  <% end %>
</div>
帖子中的

/ _each.html.erb

<% posts.each do |post| %>
  <ul><i><%= link_to post.message, post %></i></ul></br>
<% end %>

答案 1 :(得分:-1)

group_controller中没有@post变量&#39; s&#39; show&#39;行动。 可能你需要表演行动中的东西,如:

@posts = Post.where(group_id: @group.id)

此外,当您从另一个文件夹渲染部分时,您必须传递实例变量的值(如果我错了,请更正我)。 e.g

<%= render 'posts/each', {posts: @posts} %>

并通过&#39;帖子&#39;迭代而不是&#39; @ posts&#39;