我的索引文件只显示一个数据库条目

时间:2014-08-18 14:33:46

标签: ruby-on-rails controller twitter-bootstrap-3 erb

我正在尝试列出所有“坑”,这与我的应用中的“帖子”基本相同。但是,我的坑/索引仅显示创建的第一个坑而不是列出所有坑。我在视图或控制器中看不到任何错误。我感觉它的东西很小,可能需要另外一双眼睛指出它。感谢。

index.html.erb

<div class = "container list-pits"> 
  <% @pit.each do |pit| %>

 <div class = "row">

   <div class = "container">
    <div class = "well pit-well"> 
       <h3 id="pit-title"><%= link_to pit.topic, pit_path(pit) %></h3>
          <br>
            <p><%= pit.summary %></p>
            <p>Replies (<%= pit.comments.count %>)</p>
          <br>
            <p>Pit Created by: <%= link_to pit.user.name, current_user %> on <%= pit.created_at %></p>
            <%= link_to "Join Pit", '#', class: "btn btn-primary" %>
       </div>
    </div>
      <% end %>
  </div>
 </div>

pits_controller

class PitsController < ApplicationController

def new
  @pit = Pit.new
end

def index
  @pit = Pit.all
  @user = User.find_by(params[:id])
  @pit = @user.pits
  @pits = Pit.order('created_at DESC').group_by { |pit| pit.created_at.strftime("%B %Y") }
end

def create
  @user = current_user
  @pit = current_user.pits.create(pit_params)
    if @pit.save
      redirect_to @pit
    else
      render 'new'
    end
end

def show
  @pit = Pit.find(params[:id])
end

def edit
end

def update
end

private

def pit_params
    params.require(:pit).permit(:topic, :summary, :image, :video_url, :author, :user_id)
end

end

1 个答案:

答案 0 :(得分:1)

def index
  @pit = Pit.all
  @user = User.find_by(params[:id])
  @pit = @user.pits
  @pits = Pit.order('created_at DESC').group_by { |pit| pit.created_at.strftime("%B %Y") }
end

首先,您不需要@pit = Pit.all,因为您使用@pit覆盖@pit = @user.pits。 我的猜测是@user所选的id(@user = User.find(params[:id]))只有1个Pit类型的对象。

如果您想显示所有维修站,请移除@pit = @user.pits并保留@pit = Pit.all

PS:在您的创建操作中有current_user.pits.create(pit_params),之后您正在尝试@pit.save。您应该将第一个更改为current_user.pits.new(pit_params)