当我尝试运行这些代码行时,我得到“无法写入未知属性competition_id
错误”:
notification = Notification.create(
user: subscription.tournament.user,
content: "#{subscription.user.full_name} a demandé à s'inscrire à #{subscription.tournament.name} dans la catégorie #{subscription.competition.category} ",
competition: subscription.competition
)
我不明白,因为我进行了迁移,将竞争作为通知的外键添加:
class AddCompetitionToNotification < ActiveRecord::Migration
def change
add_reference :notifications, :competition, index: true, foreign_key: true
end
end
我的架构也已成功更新,表格通知似乎有外键竞争:
create_table "notifications", force: :cascade do |t|
t.integer "user_id"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "read", default: false
t.integer "convocation_id"
t.integer "tournament_id"
t.integer "competition_id"
end
add_index "notifications", ["competition_id"], name: "index_notifications_on_competition_id", using: :btree
add_index "notifications", ["user_id"], name: "index_notifications_on_user_id", using: :btree
我的竞争模式有以下关联:
class Competition < ActiveRecord::Base
belongs_to :tournament
has_many :subscriptions, dependent: :destroy
has_many :notifications, dependent: :destroy
我的通知模型
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :convocation
belongs_to :tournament
belongs_to :competition
end
这个错误来自哪里?
答案 0 :(得分:0)
您可以像这样重新排序函数调用:
notification = subscription.competition.notifications.new |n|
n.user_id = subscription.tournament.user.id
n.content = "#{subscription.user.full_name} a demandé à s'inscrire à #{subscription.tournament.name} dans la catégorie #{subscription.competition.category} "
end
notification.save!