I have been learning rails and i have stumbled one problem with relationships. I have many-to-many association User - Tournament, and for some reason i can't access participated_tournaments on User instances, or can't access participants on Tournament instances.
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'
User model
class User < ActiveRecord::Base
has_many :participants_tournaments
has_many :participated_tournaments, :through => :participants_tournaments
end
Tournament model
class Tournament < ActiveRecord::Base
has_many :participants_tournaments
has_many :participants, :through => :participants_tournaments
end
ParticipantsTournament model
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
I have read: This topic on SO, also this topic and watched/read this railscast, but i can't seem to finally get it working.
When you are calling .new on tournaments it does not have an id, so it will be nil. Therefore will not find the user.
Also when you are remapping a model in a has many through like this you have to tell active record what the model it is looking for is. You do this with the :source argument. Here is how tournament would work.
class Tournament < ActiveRecord::Base
has_many :participants_tournaments
has_many :participants, :through => :participants_tournaments, :source => :user
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With