之前一直没用过 has_one,查看了 Rails 文档也搞不清楚。想请问一下为什么 User role 更改了却保存不了?谢谢了!
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
after_initialize :default_value
private
def default_value
@profile = self.build_profile
@profile.role ||= "User"
@profile.avatar ||= ""
end
end
class Profile < ActiveRecord::Base
belongs_to :user
end
irb(main):001:0> User.first.profile
=> #<Profile id: nil, role: "User", avatar: "", user_id: 1, created_at: nil, updated_at: nil>
irb(main):002:0> User.first.profile.role = "Admin"
=> "Admin"
irb(main):003:0> User.first.profile.save
=> true
irb(main):004:0> User.first.profile
=> #<Profile id: nil, role: "User", avatar: "", user_id: 1, created_at: nil, updated_at: nil>