简体   繁体   中英

My join table doesn't seem to be working

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM