【问题标题】:First_or_initialize and nested attributesFirst_or_initialize 和嵌套属性
【发布时间】:2013-07-03 00:34:08
【问题描述】:

我有一个User 模型,基本上有一个电子邮件和一个用户名
我有一个嵌套的Profile 模型,它有一个名称、一个位置和一个描述

User 注册时,一切(除了描述)都是必需的。我有一个与这个嵌套模型完美配合的表单。

现在是 Oauth:我希望允许访问者使用他们的 GitHub 帐户进行注册。
这个方法 (RailsCast #235) 允许我初始化一个新的User自动填写 4 User 属性:提供者、uid、电子邮件和用户名。

def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_initialize do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.username = auth.info.nickname
  end
end

但我还想用 name 初始化一个嵌套的配置文件,最后用 position 填充我从 GitHub 获得的哈希信息。

我尝试放置 user.build_profile(:name => auth.info.name)user.profile.name = auth.info.name 之类的内容,但我似乎找不到如何构建这个嵌套元素。

【问题讨论】:

    标签: ruby-on-rails oauth nested-attributes


    【解决方案1】:

    我通过以下方式解决了这个问题(我使用设计和 ominauth):
    这是“注册控制器”

    # GET /resource/sign_up
    def new
       resource = build_resource({})
       # check the session exists or not
       if session["devise.user_person_attributes"]
          ### just do anything you need to do prefill the form. this works very well for me
          resource.build_person(gender: session["devise.user_person_attributes"]["gender"]) 
       else
          resource.build_person
       end
       respond_with root_path
    end
    

    对于“OmniauthCallbacksController”,我这样做:

    def all
        omniauth = request.env["omniauth.auth"]
        authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
        if authentication
            .
            .(SOME CODE OMITTED)
        elsif current_user
            .
            .
            .(SOME CODE OMITTED)
        else
            user = User.from_omniauth(omniauth)
            flash[:notice] = "Please finalize your registration"
            session["devise.user_attributes"] = user.attributes
            session["devise.user_person_attributes"] = user.person.attributes
            session["devise.auth_attributes"] = user.authentications.first.attributes
    
            redirect_to new_user_registration_url
        end
    end
    
    alias_method :twitter, :all
    alias_method :facebook, :all 
    

    这对我来说很酷!我希望这对其他人也有帮助。

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多