ruby-on-rails – Rails,has_many:通过,未定义的方法`to_sym`为nil:NilClass

我一直在学习铁轨,我偶然发现了一个关系问题.我有多对多关联用户 – 锦标赛,由于某种原因,我无法访问用户实例上的participant_tournaments,或无法访问锦标赛实例上的参与者.

2.0.0-p643 :001 > Tournament.new.participants
NoMethodError: undefined method `to_sym' for nil:NilClass
from /home/marcin/.rvm/gems/ruby-2.0.0-p643/gems/activerecord-4.1.8/lib/active_record/reflection.rb:100:in `_reflect_on_association'
from /home/marcin/.rvm/gems/ruby-2.0.0-p643/gems/activerecord-4.1.8/lib/active_record/reflection.rb:537:in `source_reflection'

用户模型

class User < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participated_tournaments, :through => :participants_tournaments
end

比赛模型

class Tournament < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participants, :through => :participants_tournaments
end

参与者锦标赛模型

class ParticipantsTournament < ActiveRecord::Base
  belongs_to :tournament
  belongs_to :user
end

参与者迁移

def change
  create_table :participants_tournaments, :id => false do |t|
    t.integer "tournament_id",
    t.integer "user_id"
  end
end

我读过了:
This topic on SO,also this topic和观看/阅读this railscast,但我似乎无法最终使它工作.

当你在锦标赛上打电话给.new时,它没有id,所以它将是零.因此不会找到用户.

此外,当您重新映射模型时,您需要告诉活动记录它正在寻找的模型是什么.您可以使用:source参数执行此操作.以下是锦标赛的运作方式.

class Tournament < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participants, :through => :participants_tournaments, :source => :user
end
翻译自:https://stackoverflow.com/questions/29269128/rails-has-many-through-undefined-method-to-sym-for-nilnilclass

转载注明原文:ruby-on-rails – Rails,has_many:通过,未定义的方法`to_sym`为nil:NilClass