【问题标题】:Whenever a User object is created, create Profile object too with devise and omniauth每当创建用户对象时,也使用设计和omniauth 创建配置文件对象
【发布时间】:2012-08-14 12:33:39
【问题描述】:

我关注了 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">

我期待名称会更新。我应该怎么做?

谢谢

【问题讨论】:

  • 当你使用save!而不是save时会发生什么
  • 好吧,我假设什么都没有,因为常规保存方法返回 true。
  • PriteshJ,同样的情况。我认为我声明属性的方式有问题。刚刚发现 p["name"]="Adam" 有效。为什么不 p.name="Adam"?

标签: ruby-on-rails devise omniauth railscasts


【解决方案1】:

试试:

 accepts_nested_attributes_for :profile

在您的用户模型中

【讨论】:

    【解决方案2】:

    我想我发现了问题所在。 “名称”是保留属性。我将其更改为“owner_name”,现在 p.owner_name="Adam" 有效。我不知道我不应该使用“名称”作为属性。

    谢谢大家!

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2011-06-06
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多