如何使用devise gem在after_confirmation方法中使用update_all方法?

时间:2020-01-28 06:09:36

标签: ruby-on-rails devise

在为特定学校创建新原则时,如何将principle :status更新为true,并将先前原则:status的记录更新为{{1 }}。

我有false模型:

Principle

我有class Principle < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable belongs_to :school def default_values self.status = false end def active_for_authentication? super && status? end def after_confirmation Principle.update_all status: false self.update_attribute(:status, true) end end 模型:

School

Schema.rb:

class School < ApplicationRecord
    has_many :principles, dependent: :destroy
end

在邮件的 create_table "principles", force: :cascade do |t| t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.integer "school_id" t.boolean "status", default: false t.string "encrypted_password", default: "", null: false t.string "username" t.string "email" t.datetime "remember_created_at" t.datetime "reset_password_sent_at" t.string "reset_password_token" t.integer "failed_attempts" t.string "unlock_token" t.string "unconfirmed_email" t.datetime "confirmation_sent_at" t.datetime "confirmed_at" t.string "confirmation_token" t.index ["school_id"], name: "index_principles_on_school_id" end 模型Principle中,我想将最后一个确认原则的after_confimation更新为:status,并将true更新为{{ 1}}该学校以前的原则。

1 个答案:

答案 0 :(得分:0)

更改此:

def after_confirmation
  Principle.update_all status: false
  self.update_attribute(:status, true)
end

对此:

def after_confirmation
school = self.school    # this line is not necessary, you can get rid of it
school.principles.update_all(status: false)
self.update_attribute(:status, true)
end