Reputation: 5526
I have seen multiple questions similar to this, but none worked for me.
I have a team model:
class Team < ActiveRecord::Base
has_one :p1, :class_name => "Player", :foreign_key => 'player_id', :validate => true
has_one :p2, :class_name => "Player", :foreign_key => 'player_id', :validate => true
end
in my team's _form.html.erb, I am referring to players as
<%= f.collection_select :p1, Player.all, :id, :name %>
However, on form submission, I see the error:
Player(#28401456) expected, got String(#14111904)
Application Trace | Framework Trace | Full Trace
app/controllers/teams_controller.rb:47:in `new'
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"GSIcEvROFnvgGWT4HvE2VNqRw4NxU1J8iAw/WhZeRLk=",
"team"=>{"p1"=>"1"},
"commit"=>"Create Team"}
And here is the code at line
def create
@team = Team.new(params[:team])
.....
end
Any ideas please?
Upvotes: 4
Views: 6941
Reputation: 5526
Finally, this worked:
<%= f.collection_select :p1_id, Player.all, :id, :name %>
Here is the magic: My migration has t.references p1 and that created a column of p1_id in the database. When The form is submitted, rails is looking to fill in the id of the reference at:
def create
@team = Team.new(params[:team])
.....
end
Upvotes: 6
Reputation: 474
Try this:
<%= f.collection_select :player_id, Player.all, :id, :name %>
Upvotes: 0
Reputation: 45094
I could be wrong, but my guess is that instead of
<%= f.collection_select :p1, Player.all, :id, :name %>
you need
<%= f.collection_select :p1, :team_id, Player.all, :id, :name %>
Upvotes: 0