Reputation: 27124
my models:
class CardSignup < ActiveRecord::Base
has_one :conversion
has_one :card_signup, :through => :conversion
class User < ActiveRecord::Base
has_many :conversions
has_many :card_signups, :through => :conversions
class Conversion < ActiveRecord::Base
belongs_to :card_signup
belongs_to :user
end
my migration:
class AddCardSignupConversions < ActiveRecord::Migration
def self.up
create_table (:conversions, :id => false) do |t|
t.integer :user_id
t.integer :card_signup_id
end
end
def self.down
drop_table :conversions
end
end
Now, I can successfully look up:
User.find(x).conversions
CardSignup.find(x).conversion
However, I can't add any objects to these links. Not sure why.. I tried this :
User.last.conversions << CardSignup.last
Which returned :
ActiveRecord::AssociationTypeMismatch: Conversion(#2183228680) expected, got CardSignup(#2183113520)
Why is that?
Upvotes: 0
Views: 48
Reputation: 27124
Ok I got it!
class CardSignup < ActiveRecord::Base
# add_column :card_signups, :converted_by, :integer # Add this to your migration
belongs_to :converted_by, :class_name => "User"
class User < ActiveRecord::Base
has_many :conversions, :foreign_key => :converted_by, :class_name => "CardSignup"
This allows me to have my own unique name for the relationship.
Upvotes: 0
Reputation: 5192
Why have you declared keys as strings in conversions table? Usually integers are used. This could be a cause of a problem
t.string :user_id
t.string :card_signup_id
Edit: Also you're trying to add CardSignup to conversions association. This definitely will not work. Btw: error says the same.
Upvotes: 2