這裏是我的用戶模型保存方法不寫入數據庫
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :personas
has_many :stories, through: :persona
validates_presence_of :name
attr_accessor :name, :default_persona_id
after_create :create_first_persona
private
def create_first_persona
@persona = Persona.new
@persona.user = self
@persona.name = self.name
if @persona.save
make_first_persona_default
end
end
def make_first_persona_default
@user = self
@user.default_persona_id = @user.personas.first.id
@user.save!(:validate => false)
end
end
它所做的是,在每次創建人物角色一個用戶註冊,然後將這種生活的ID作爲用戶default_persona_id。
一切正常,除了make_first_persona_default
。當我在rails控制檯中檢查用戶時,default_persona_id是零。
我on Rails的4
UPDATE
編輯make_first_persona_default到泰倫東的
def make_first_persona_default
unless self.update_attribute(:default_persona_id, self.personas.first.id)
raise "got an error trying to save persona: #{self.errors.inspect}"
end
end
default_persona_id仍然是零
User Load (1.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 13, email: "[FILTERED]", encrypted_password: "[FILTERED]", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2013-10-01 02:09:19", last_sign_in_at: "2013-10-01 02:09:19", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2013-10-01 02:09:19", updated_at: "2013-10-01 02:09:19", default_persona_id: nil>
這裏是我的,用戶模式。
create_table "users", force: true 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.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "default_persona_id"
end
和我用來添加default_persona_id列的遷移。
class AddActivePersonaToUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.integer :default_persona_id
end
end
end
啊!讓我試試這個。 –
這就是問題所在! –