2013-03-27 47 views
2

我已经看到类似这样的多个问题,但都没有为我工作。栏杆对象预期得到字符串

我有一个团队模式:

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 

在我的团队的_form.html.erb,我指的是球员

<%= f.collection_select :p1, Player.all, :id, :name %> 

然而,在表单提交,我看到的错误:

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"} 

这里是线

def create 
    @team = Team.new(params[:team]) 
    ..... 
end 

任何想法的代码吗?

回答

5

最后,工作:

<%= f.collection_select :p1_id, Player.all, :id, :name %> 

这里是魔法: 我的迁移有t.references P1并在数据库中创建p1_id列。 当表单提交,轨道正在寻找在参考的ID填写:

def create 
    @team = Team.new(params[:team]) 
    ..... 
end 
+1

感谢这 - 非常误导性的错误信息 - 应该告诉我们列名不匹配,并且将是一个20秒的修复,而不是一个小时 – JosephK 2015-11-17 19:13:03

+0

对此不能感谢。这也适用于铁轨5的强烈参数。 – 2017-04-22 16:50:09

0

试试这个:

<%= f.collection_select :player_id, Player.all, :id, :name %> 
+0

嗯,我看到下列错误:NoMethodError在团队#新 显示曲目/应用/视图/团队/ _form.html.erb其中行#14提出: 未定义的方法'合并”为:名称:符号 提取的源(围绕线#14): 11:

12:<% end %> 13: 14:<% = f.collection_select:p1,:player_id,Player.all,:id,:name%> 15:<! - <%= f.select:p1,Player.all.collect {| e | [e.name,e.id]}%> - > 16: 17:
Kiran 2013-03-27 20:09:27

0

我可能是错的,但我的猜测是不是

<%= f.collection_select :p1, Player.all, :id, :name %> 

你需要

<%= f.collection_select :p1, :team_id, Player.all, :id, :name %> 

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

+0

I see the error: NoMethodError in Teams#new Showing track/app/views/teams/_form.html.erb where line #14 raised: undefined method 'merge' for :name:Symbol Extracted source (around line #14): 11:

12:<% end %> 13:14:<%= f.collection_select:p1,:id,Player.all,:id,:name %> 15:<! - <%= f.select:p1,Player.all.collect {| e | [e.name,e.id]}%> - > 16:17:
Kiran 2013-03-27 20:11:16

+0

对不起,我原来的回答是错误的。我更新了它。再试一次? – 2013-03-27 20:13:16

+0

嗯,回到原点。这是产生p1 [team_id],我想要的是团队[p1] ..基本上上述是导致错误的行为。我必须切换到我的原始形式'<%= f.collection_select:p1,Player.all,:id,:name%>',因为团队自动从f来。然而,这使我回到我发布的原始问题:( – Kiran 2013-03-27 21:36:28

相关问题