Reputation: 13347
I am trying to modify the create
method of my controller to custom build this object.
The scenario is a modal window displays a form which has an autocomplete text field that loads in platform names via AJAX, then the user submits the form, the create
method looks up the Platform
by the name in the text box, and adds it to the current_user.game
collection...
I have a simple has_many
relationship from Game
to Platform
1 def create
2 platform = Platform.where(:short_name => params[:platform])
3
4 game = Game.new(game_params)
5 game.platform << platform
6 current_user.games << game
7 render :nothing
8 end
I am getting an error undefined method '<<' for nil:NilClass
on line 5.
I don't know if this is how this should be done... How should I try to accomplish this?
Upvotes: 0
Views: 1321
Reputation: 13347
So I had the association wrong in my models (forgot to add it) and also I had a platform
column of type string
in my Game
table instead of a platform_id
column of type `integer.
After updating that I began getting the an ActiveRecordTypeMismatch
error which it was expecting the type Platform
but found ActiveRecord::Record::Association
(or something like that).
Also apparently when assigning to the belongs_to
side of an association use =
instead of <<
.
Below is the updated working controller create
method
game = Game.new(game_params)
game.platform = Platform.where(:short_name => params[:platform]).first
current_user.game << game
render :nothing
Upvotes: 0
Reputation: 8003
You are missing a s
?
game.platforms << platform
#------------^-------------
Upvotes: 1