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

时间:2015-03-26 00:37:18

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

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

ParticipantsTournament模型

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

ParticipantsTournament migration

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

我看过: This topic on SOalso this topic并观看/阅读this railscast,但我似乎终于无法正常工作。

1 个答案:

答案 0 :(得分:19)

当您在锦标赛上致电.new时,它没有id,因此它将是nil。因此不会找到用户。

此外,如果您正在重新映射模型,那么您必须告诉活动记录它正在寻找的模型是什么。您使用:source参数执行此操作。以下是锦标赛的运作方式。

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