我在进行一些多对多关系的同时不断收到ActiveRecord :: AssociationTypeMismatch。
我尝试过更改模型的名称,即
has_many :subscribers, through: :rafflecontestants, source: :users
但这使我无处可去。
class Rafflecontestant < ApplicationRecord
belongs_to :user
belongs_to :raffle
end
class Raffle < ApplicationRecord
validates :name, presence: true
has_many :rafflecontestants
has_many :users, through: :rafflecontestants
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :rafflecontestants
has_many :raffles, through: :rafflecontestants
end
和我的模式:
create_table "rafflecontestants", force: :cascade do |t|
t.integer "user_id"
t.integer "raffle_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["raffle_id"], name: "index_rafflecontestants_on_raffle_id"
t.index ["user_id"], name: "index_rafflecontestants_on_user_id"
end
create_table "raffles", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "winner"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "is_admin"
t.string "authentication_token", limit: 30
t.index ["authentication_token"], name: "index_users_on_authentication_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
在控制台中复制的步骤:
u = User.create(...)
r= Raffle.create(..., Rafflecontestants: [u])
ActiveRecord::AssociationTypeMismatch: Rafflecontestant(#66411640) expected, got #<User id: 1, email: "name@pnimedia.com", created_at: "2019-07-11 19:54:55", updated_at: "2019-07-11 19:54:55", is_admin: false, authentication_token: "yeU3mgQQPyXqDrMBFPAY"> which is an instance of User(#73796060)
我希望使用Rafflecontestants
表将用户添加到抽奖活动中。
答案 0 :(得分:1)
您不太正确地采用这种方式。
这两个都应该起作用,有关更多信息,请访问the guides
user = User.create(...)
raffle = Raffle.create(...)
raffle.users << user
或...
user = User.create(...)
raffle = Raffle.create(...)
user.raffles << raffle
如果联接模型Rafflecontestant
上具有额外的属性,则必须这样做
user = User.create(...)
raffle = Raffle.create(...)
Rafflecontestant.create(user: user, raffle: raffle, some_extra_attribute: 1)
答案 1 :(得分:0)
ApplicationRecord是否从ActiveRecord :: Base继承?
我使用ActiveRecord::Base
进行了尝试,并且对我有用
user = User.create!
user.raffles.create!(name: "new raffle")
raffle = Raffle.last
user.rafflecontestants
# [#<Rafflecontestant:0x00007fda70313948 id: 1, user_id: 1, raffle_id: 1>]