保存数据时的AssociationTypeMismatch问题
Posted
技术标签:
【中文标题】保存数据时的AssociationTypeMismatch问题【英文标题】:AssociationTypeMismatch problem when saving data 【发布时间】:2010-12-04 02:55:41 【问题描述】:在上一个问题中我被难住了.. 但是堆栈溢出提供了解决方案
我的两个模型
class Team < ActiveRecord::Base
has_many :fixtures, :finder_sql => 'SELECT * FROM fixtures where (home_team = #id or away_team = #id)'
has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team
has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team
has_many :teamalias
end
class Fixture < ActiveRecord::Base
belongs_to :league
belongs_to :selection
has_many :selection
named_scope :for_team_id, lambda|team_id| :conditions => ['(home_team = ? or away_team = ?)', team_id, team_id]
belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team
belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team
def fix_list
[home_team.title, "Draw", away_team.title]
end
end
取自 Multi level associations in rails
但我又被难住了——我正试图根据上面第一个答案中的最后一个解决方案保存一个夹具,但我得到了一个类型不匹配的结果。
团队(#38391330)预期,得到字符串(#1242130)
不知道该怎么做,请帮忙。
edit- db 迁移
这里是迁移
类 CreateFixtures
t.timestamps
end
结束
def self.down drop_table :夹具 结尾 结束
类 CreateTeams
t.timestamps
end
结束
def self.down drop_table:团队 结尾 结束
类 AddResultToFixture
def self.down remove_column :fixtures, :result 结尾 结束
【问题讨论】:
能否分享一下相关的数据库架构? 您能否显示代码以及出现此错误的位置? 【参考方案1】:您的表单可能有fixture[home_team]
,这是一个通过team.id
的选择
所以当你这样做时
@fixture = Fixture.new(params[:fixture])
@fixture.save
您正在调用home_team= team.id
team.id 是一个字符串,但 home_team 应该是一个 Team 对象
【讨论】:
以上是关于保存数据时的AssociationTypeMismatch问题的主要内容,如果未能解决你的问题,请参考以下文章