每当创建User对象时,也可以使用devise和omniauth创建Profile对象

时间:2012-08-18 06:11:24

标签: ruby-on-rails devise omniauth railscasts

我跟随Ryan Bates#235 Devise和OmniAuth(修订版)http://railscasts.com/episodes/235-devise-and-omniauth-revised并且能够使它发挥作用。

现在,我想向用户添加个人资料。

所以,我试过了......

def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.username = auth.info.nickname
      user.profile = user.build_profile
      user.profile.name = auth.info.name
      user.profile.save
    end
  end
乍一看,一切似乎都没问题。但我注意到它没有更新“名称”属性。

1.9.3p125 :019 > Profile.last
  Profile Load (0.4ms)  SELECT "profiles".* FROM "profiles" ORDER BY "profiles"."id" DESC LIMIT 1
 => #<Profile id: 8, user_id: 3, name: nil, created_at: "2012-08-18 06:00:59", updated_at: "2012-08-18 06:00:59">

所以我试着设置一个值,这就是发生的事情:

 1.9.3p125 :020 > p=Profile.last
  Profile Load (0.4ms)  SELECT "profiles".* FROM "profiles" ORDER BY "profiles"."id" DESC LIMIT 1
 => #<Profile id: 8, user_id: 3, name: nil, created_at: "2012-08-18 06:00:59", updated_at: "2012-08-18 06:00:59">
1.9.3p125 :021 > p.name = "Adam"
 => "Adam" 
1.9.3p125 :022 > p.save
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT
 => true 
1.9.3p125 :023 > p.name
 => "Adam" 
1.9.3p125 :024 > p
  => #<Profile id: 8, user_id: 3, name: nil, created_at: "2012-08-18 06:00:59", updated_at: "2012-08-18 06:00:59">

我原以为该名称会更新。我该怎么办?

由于

2 个答案:

答案 0 :(得分:1)

尝试:

 accepts_nested_attributes_for :profile
用户模型中的

答案 1 :(得分:0)

我想我发现了什么问题。 “name”是保留属性。我将其更改为“owner_name”,现在p.owner_name =“Adam”正常工作。我不知道我不应该使用“name”作为属性。

谢谢大家!