如何在Ruby on Rails中访问数据?

时间:2017-07-23 16:44:08

标签: ruby-on-rails

我制作了一个脚手架,我将index.html.erb中的代码转移到另一个文件show_league.html.erb中,这样我的index.html.erb将成为我的主页,show_league.html.erb将显示所有联盟创造了。现在当我访问show_league.html.erb时,它给了我这个错误:

联盟中的NoMethodError#show_league 未定义的方法`每个'为零:NilClass

这是我的show_league.html.erb(首先是index.html.erb中包含的代码):

<thead>
    <tr>
        <th>League name</th>
        <th>Commissioner</th>
        <th>League manager</th>
        <th>Venue of games</th>
        <th colspan="3"></th>
    </tr>
</thead>

<tbody>
    <% @leagues.each do |league| %>
        <tr>
            <td><%= league.league_name %></td>
            <td><%= league.commissioner %></td>
            <td><%= league.league_manager %></td>
            <td><%= league.venue_of_games %></td>
            <td><%= link_to 'Show', league %></td>
            <td><%= link_to 'Edit', edit_league_path(league) %></td>
            <td><%= link_to 'Destroy', league, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
    <% end %>
</tbody>


请帮帮我。

2 个答案:

答案 0 :(得分:2)

一般的Rails约定是在indexshow上提供所有数据,以便为相关索引的特定实例提供数据。

def index
    @leagues = League.all
end

def show
    @league = League.find(params[:id])
end

如果您需要,可以违反此惯例,但您应该有理由这样做。如果你不需要它,任何方法都可以是空白的,如果你想要联盟的所有数据应该是index,如果你想要一个特定的联盟它应该是show

答案 1 :(得分:0)

在您需要的LeaguesController

def show_league
  @leagues = League.all
end