保存数据时的AssociationTypeMismatch问题

时间:2009-10-05 23:35:00

标签: ruby-on-rails

在之前的一个问题中,我被困了..但是堆栈溢出提供了解决方案

我的两个模特

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)期待,得到String(#1242130)

不知道该怎么做,请帮忙。

编辑 - 数据库迁移

以下是迁移

class CreateFixtures&lt; ActiveRecord的::迁移   def self.up     create_table:fixtures do | t |       t.integer:home_team       t.integer:away_team       t.datetime:什么时候       t.integer:league_id

  t.timestamps
end

def self.down     drop_table:灯具   结束 端

类CreateTeams&lt; ActiveRecord的::迁移   def self.up     create_table:团队做| t |       t.string:title

  t.timestamps
end

def self.down     drop_table:团队   结束 端

class AddResultToFixture&lt; ActiveRecord的::迁移   def self.up     add_column:fixtures,:result,:integer   端

def self.down     remove_column:fixtures,:result   结束 端

1 个答案:

答案 0 :(得分:1)

您的表单可能有fixture[home_team],这是一个通过team.id

的选择

所以当你这样做时

@fixture = Fixture.new(params[:fixture])
@fixture.save

你正在调用home_team= team.id team.id是一个字符串,但home_team应该是一个Team对象