为什么我的控制器没有显示所有belongs_to对象?

时间:2015-10-25 20:43:38

标签: ruby-on-rails ruby-on-rails-4

我有两种模式:锦标赛和圆形。

class Tournament < ActiveRecord::Base

  belongs_to :user
  has_many :rounds

  validates :name, presence: true, length: { in: 3..64 }
  validates :description, length: { maximum: 160 }
  validates :number_of_rounds,  :numericality => { :greater_than => 0 }

end

圆形模型:

class Round < ActiveRecord::Base
  belongs_to :tournament, dependent: :destroy
end

该模型的控制器:

class RoundsController < ApplicationController
  def index
    @rounds = @tournament.rounds
  end

  def new
    @round = Round.new
    render action: 'new'
  end

  def create
    #@round = Round.new(round_params)
  end

  def show
  end

  def destroy
  end

 private

   def round_params
     params.require(round).permit(:tournament_id)
   end
end

到目前为止,一切都很好,但我可以展示各种比赛。当我尝试这样做时,控制台会显示以下错误:

undefined method `rounds' for nil:NilClass

我从这个网站尝试过很多解决方案,但都没有。

这是索引操作的视图:

.container
%h2 Rounds
  -if @rounds.any?
    .row
        -@rounds.each do |round|
            .col-md-2.round
                %h3 Round #{round.number}
                %p Tournament id: #{round.tournament_id}
-else
    .jumbotron
        %p This tournament has not yet any rounds.

3 个答案:

答案 0 :(得分:1)

undefined method `rounds' for nil:NilClass

表示未在Rounds控制器中定义类锦标赛。 您的锦标赛模型定义锦标赛有多个轮次,而您的圆形模型定义一轮属于锦标赛。

所以基本上,如果你想显示他们所属的锦标赛的所有轮次和id,你的控制器应该是这样的:

      def index
         @rounds = Rounds.all
      end

并假设您的圆桌会议中有一个tournament_id列作为您关系的外键,您的观点可能如下:

        <div class="container">
          <h2>Rounds</h2>
           <% @rounds.each do |round| %>
              <div class="row">
                <div class="col-md2">
                  <h3>Round <%= round.number %></h3>
                  <p>Tournament id: <%= round.tournament_id %></p>
                </div>
              </div>
           <% end %>
        </div>

答案 1 :(得分:0)

锦标赛未定义。你的锦标赛资源应该嵌套在里面,然后你应该在你的索引方法中找到一个Tournament.find(params [:tournament_id])锦标赛。

答案 2 :(得分:0)

最后,我解决了我的问题,这比我想象的要容易。 我在tournaments_controller中添加了两行代码:`

`   def show
        @tournament = Tournament.find(params[:id])
        @rounds = @tournament.rounds
    end 

我更新了我对锦标赛表演行动的看法:

    -if @rounds.any?
      .row
        -@rounds.each do |round|
          .col-md-2.round
            %h3 Round #{round.number}
            %p Tournament id: #{round.tournament_id}
相关问题