R – AssociationTypeMismatch problem when saving data

ruby-on-rails

in a previous question i was stumped.. but stack overflow provided the solution

my two models

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

taken from
Multi level associations in rails

but I'm stumped again- i'm trying to save a fixture based on the last solution in the first answer above and I am getting a typemismatch of.

Team(#38391330) expected, got String(#1242130)

no idea what to do here please help.

edit- db migrations

Here is the migrations

class CreateFixtures < ActiveRecord::Migration
def self.up
create_table :fixtures do |t|
t.integer :home_team
t.integer :away_team
t.datetime :when
t.integer :league_id

  t.timestamps
end

end

def self.down
drop_table :fixtures
end
end

class CreateTeams < ActiveRecord::Migration
def self.up
create_table :teams do |t|
t.string :title

  t.timestamps
end

end

def self.down
drop_table :teams
end
end

class AddResultToFixture < ActiveRecord::Migration
def self.up
add_column :fixtures, :result, :integer
end

def self.down
remove_column :fixtures, :result
end
end

Best Answer

your form probably has fixture[home_team] which is a select which passes the team.id

so when you do

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

you are calling home_team= team.id team.id is a string but home_team should be a Team object

Related Topic