Rails,has_many:通过,未定义的方法`to_sym`为nil:NilClass

Mar*_*cin 8 ruby activerecord ruby-on-rails ruby-on-rails-4

我一直在学习铁轨,我偶然发现了一个关系问题.我有多对多关联用户 - 锦标赛,由于某种原因我无法访问用户实例上的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'
Run Code Online (Sandbox Code Playgroud)

用户模型

class User < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participated_tournaments, :through => :participants_tournaments
end
Run Code Online (Sandbox Code Playgroud)

比赛模型

class Tournament < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participants, :through => :participants_tournaments
end
Run Code Online (Sandbox Code Playgroud)

参与者锦标赛模型

class ParticipantsTournament < ActiveRecord::Base
  belongs_to :tournament
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

参与者迁移

def change
  create_table :participants_tournaments, :id => false do |t|
    t.integer "tournament_id",
    t.integer "user_id"
  end
end
Run Code Online (Sandbox Code Playgroud)

我已经读过: 关于SO的这个主题,也是这个主题并观看/阅读这个railscast,但我似乎无法最终得到它的工作.

Aus*_*tio 19

当你打电话.new参加锦标赛时它没有id,所以它会nil.因此不会找到用户.

此外,当您重新映射模型时,您需要告诉活动记录它正在寻找的模型是什么.你用这个:source参数做到这一点.以下是锦标赛的运作方式.

class Tournament < ActiveRecord::Base
  has_many :participants_tournaments
  has_many :participants, :through => :participants_tournaments, :source => :user
end
Run Code Online (Sandbox Code Playgroud)