2015-12-10 37 views
11

Bu gönderiyı düzenli toparlamaya çalıştım, bu yüzden yeni gelenler için bu kadar uzun görünmüyor. Aşağıdaki cevaplarda başkalarının önerilerini takip ederek ortaya çıkan hataları içerir. Raylar 4 - kurulum, yeni kullanıcı oluştururken otomatik olarak profil oluştur

Rails 4.

ben hazırlamak ve omniauth kullanmak sahip bir uygulama yapmaya çalışıyorum.

Kullanıcı ve profil için modellerim var. Kullanıcının bir profili vardır ve profili kullanıcıya aittir.

Amacım, kullanıcı modelinin gerçekten dokunmadığı her şey için kullanıcı modelini kullanmaktır. Kullanıcının tuttuğu şeyler için profil modelini kullanıyorum.

Yeni bir kullanıcı oluşturulduğunda, kullanıcının kullanıcı modelinde oluşturulan ayrıntılarla kısmen doldurulması gereken profil sayfasına yönlendirilmesini istiyorum.

Sorun yaşıyorum.

Ben:

User.rb

has_one :profile 

Profile.rb

belongs_to :user 

Omniauth_callbacks_controller.rb geri yönlendirmek Ben de çağrısında çalıştık

if @user.persisted? 
    sign_in_and_redirect_user(:user, authentication.user.profile) 
    set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format? 
else 
    session["devise.#{provider}_data"] = env["omniauth.auth"] 
    redirect_to new_user_registration_url 
end 

:

sign_in_and_redirect @user, event: :authentication 

profilleri/show.html.erb

<div class="container-fluid"> 
    <div class="row"> 
     <div class="col-xs 8 col-xs-offset-1"> 
      <%= @profile.user.formal_name %> 


      <%= @profile.occupation %> 
      <%= @profile.qualification.awards %> 
      <%= @profile.overview %> 
      <%= @profile.research_interests %> 

     </div> 

     <div class="col-xs 3"> 
      <div class="geobox"> 
      <%= render 'addresses/location' %> 
      <%= @profile.working_languages %> 
      <%= @profile.external_profile %> 

      </div> 
     </div> 
    </div> 

    <div class="row"> 
     <div class="col-xs 10 col-xs-offset-1"> 
      <%= render 'profiles/activity' %> 
     </div> 
    </div> 

</div> 

Ben de denedim

<% if user_signed_in? %> 
        Hi <%= link_to(current_user.first_name.titlecase, profile_path(current_user)) %></span> 

_nav.html.erb:

_nav.html.erb

<% if user_signed_in? %> 
        Hi <%= link_to(current_user.first_name.titlecase, user_profile_path(current_user.profile)) %></span> 

Yeni bir kullanıcının profil sayfasına gitmesine izin vermek için bir çeşit işlevsellik eklemek için ne yapmam gerekiyor?

Şu anda, giriş yapıp nav çubuğu bağlantısına tıklamayı denediğimde, profil sayfasına gitmek istiyorum. Bunun yerine, aradığım sayfanın mevcut olmadığını belirten bir hata mesajına gidiyorum. Aradığı yol profilde başlar (kullanıcı/profil yerine) - eğer bir ipucu ise emin değil.

Benim yolları şunlardır:

Profilleri:

profiles GET  /profiles(.:format)     profiles#index 
         POST  /profiles(.:format)     profiles#create 
      new_profile GET  /profiles/new(.:format)    profiles#new 
      edit_profile GET  /profiles/:id/edit(.:format)   profiles#edit 
       profile GET  /profiles/:id(.:format)    profiles#show 
         PATCH  /profiles/:id(.:format)    profiles#update 
         PUT  /profiles/:id(.:format)    profiles#update 
         DELETE /profiles/:id(.:format)    profiles#destroy 

Kullanıcı:

user_password POST  /users/password(.:format)    devise/passwords#create 
     new_user_password GET  /users/password/new(.:format)   devise/passwords#new 
     edit_user_password GET  /users/password/edit(.:format)   devise/passwords#edit 
         PATCH  /users/password(.:format)    devise/passwords#update 
         PUT  /users/password(.:format)    devise/passwords#update 
cancel_user_registration GET  /users/cancel(.:format)    users/registrations#cancel 
     user_registration POST  /users(.:format)      users/registrations#create 
    new_user_registration GET  /users/sign_up(.:format)    users/registrations#new 
    edit_user_registration GET  /users/edit(.:format)     users/registrations#edit 
         PATCH  /users(.:format)      users/registrations#update 
         PUT  /users(.:format)      users/registrations#update 
         DELETE /users(.:format)      users/registrations#destroy 
     user_confirmation POST  /users/confirmation(.:format)   devise/confirmations#create 
    new_user_confirmation GET  /users/confirmation/new(.:format)  devise/confirmations#new 
         GET  /users/confirmation(.:format)   devise/confirmations#show 
      user_unlock POST  /users/unlock(.:format)    devise/unlocks#create 
     new_user_unlock GET  /users/unlock/new(.:format)   devise/unlocks#new 
         GET  /users/unlock(.:format)    devise/unlocks#show 
      finish_signup GET|PATCH /users/:id/finish_signup(.:format)  users#finish_signup 

YENİ GİRİŞİMİ:

resources :users do 
    resources :profile 
    end 
: Daha altta öneri, ben gibi kaynakları iç içe

ve yönlendirme değiştirildi: NoMethodError (tanımlanmamış yöntemi 'profile nil için: NilClass):

sonraki girişim:

Yukarıdakilerin tümü tutmak

def self.provides_callback_for(provider) 
    class_eval %Q{ 
     def #{provider} 
     @user = User.find_for_oauth(env["omniauth.auth"]) 

     if @user.persisted? 
      sign_in_and_redirect [current_user, current_user.profile || current_user.build_profile] 

      set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format? 
     else 
      session["devise.#{provider}_data"] = env["omniauth.auth"] 
      redirect_to new_user_registration_url 
     end 
     end 
    } 
    end 

bu hata olsun

def self.provides_callback_for(provider) 
    class_eval %Q{ 
     def #{provider} 
     @user = User.find_for_oauth(env["omniauth.auth"]) 

     if @user.persisted? 
      sign_in_and_redirect [@user, @user.profile || @user.build_profile] 

      set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format? 
     else 
      session["devise.#{provider}_data"] = env["omniauth.auth"] 
      redirect_to new_user_registration_url 
     end 
     end 
    } 
    end 

RuntimeError (Could not find a valid mapping for [#<User id: 1 ... 

ve sonra kullanıcı tablosundaki tüm özelliklerin listeler ve sonra gösterir: ama şöyle yönlendirmeyi değiştirmeyi deneyin

#<Profile id: nil, user_id: 1, 

profilleri tablosundaki tüm nitelikler izledi.

YENİ BİR Ben bu yazı bulundu

GİRİŞİMİ: Rails Trying to create a profile after the user has been created

Ve ekleyerek denedim:

after_create do 
    create_user_profile 
    end 

benim kullanıcı modeline. Ben (Alexei önerisini izleyen) vardı ve tekrar denedi olarak

Ben Yönlendirme aynı tuttu.

RuntimeError (Could not find a valid mapping for [#<User id: 1 

herkes bu çözmek için nasıl görebiliyor:

Ben aynı hata mesajı alıyorum?

başka bir girişimle: (kullandığım) Raylar 4 için diyor Ruby on Rails - Creating a profile when user is created

, ben sadece bu geri arama gerekir::

after_create: create_profile

Sonra bu yazı bulundu Bunu çalıştığınızda

, yukarıdaki ile aynı hatayı alıyorum.

BİR FİKİR:

benim profil denetleyicisi için iskele jeneratör kullanılır.yöntemini oluşturmak listem

geçerli:

def create 
    @profile = Profile.new(profile_params) 

    respond_to do |format| 
     if @profile.save 
     format.html { redirect_to @profile } 
     format.json { render :show, status: :created, location: @profile } 
     else 
     format.html { render :new } 
     format.json { render json: @profile.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

özellikle bu yöntemde referans verilmeyen kullanıcı kimliği ile ilgisi belki bir şeyler bu hata mı. Profil denetleyicisinin güçlü paramlarında beyaz listeye aldım.

YENİ BİR GİRİŞİMİ

Bu makale create_profile yerine build_profile kullanarak önerir. Bunu kaydetmek ve ben aynı hatayı alıyorum çalıştığınızda

https://stackoverflow.com/questions/8337682/create-another-model-upon-user-new-registration-in-devise 

Ben

after_create :build_profile 

benim user.rb değiştirdi.

BAŞKA DENEMESİ

bu yazı içinde Matt'in cevabı ben build_profile bir tanımını içermelidir zorunda olduğunu göstermektedir

:

after_create :build_profile 

    def build_profile 
    Profile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly. 
    end 

Ne zaman: Ben benim user.rb değişti

after_create :build_profile 

    def build_profile 
    Profile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly. 
    end 

Bunu kaydedip deniyorum, benzer bir hata alıyorum ama daha fazla bilgi. günlükleri hala gösterir:

SQL (2.9ms) INSERT INTO "profiles" ("user_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["user_id", 1], ["created_at", "2015-12-18 21:58:49.993866"], ["updated_at", "2015-12-18 21:58:49.993866"]] 
2015-12-18T21:58:49.966648+00:00 app[web.1]: Profile Load (1.5ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT 1 [["user_id", 1]] 
2015-12-18T21:58:50.007428+00:00 app[web.1]: Completed 500 Internal Server Error in 113ms (ActiveRecord: 21.8ms) 
2015-12-18T21:58:49.941385+00:00 app[web.1]: User Load (1.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]] 

bu teklifi sorun üzerinde herhangi bir ışık mı:

RuntimeError (Could not find a valid mapping for [#<User id: 1, 

Ama bu hata mesajının sonuçta

, bu bilgilerin bu yeni parçası verir?

GÜNCELLEME Ben (kod herhangi bir değişiklik yapmadan) yine bu çalıştı. Şimdi bir hata alıyorum, ama bu sefer günlükleri ki:

RuntimeError (Could not find a valid mapping for [#<User id: 1, first_name: "Me", last_name: "Ma", email: "[email protected]", encrypted_password: "$2a$jqQn..HSvlcNtfAH/28.DQoWetO...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 16, current_sign_in_at: "2015-12-15 09:57:14", last_sign_in_at: "2015-12-15 09:27:07", current_sign_in_ip: #<IPAddr: IPv4:49.191.55>, last_sign_in_ip: #<IPAddr: IPv4:49.191.135.255.255>, confirmation_token: nil, confirmed_at: "2015-12-15 09:02:58", confirmation_sent_at: "2015-12-15 08:42:48", unconfirmed_email: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil, created_at: "2015-12-09 23:53:20", updated_at: "2015-12-15 09:57:14", image: nil>, #<Profile id: 1, user_id: 1, title: nil, hero_image: nil, overview: nil, occupation: nil, external_profile: nil, working_languages: nil, created_at: "2015-12-18 21:58:49", updated_at: "2015-12-18 21:58:49">]): 

bu kez profili Daha önce 1 bir kullanıcı kimliği anahtarı olmasıdır fark bu nil.

+0

nasıl 'tırmık routes' kullanıcı ve profil yolları arıyor kullanabilir? :) – davidwessman

+0

Merhaba David, onları – Mel

+0

'un üzerine kopyaladım "Aradığı yol profilde başlar (kullanıcı/profil yerine) - eğer bir ipucu ise emin değil." Her kullanıcı bağlantısının benzersiz bir profile sahip olmasını mı istersiniz? Yoksa ilk profili almak için 'domain/profile/1' adresini ziyaret edebilmek mi istiyorsunuz? – davidwessman

cevap

0

Geri arama denetleyicinize sing_in_and_redirect_user eklediniz. Size yönlendirdiği yolu düzenlemek için, applications_controller ürününüzde after_sign_in_path_for'u geçersiz kılın ve düzenleyin.

class ApplicationController < ActionController::Base 
    def after_sign_in_path_for(resource) 
    request.env['omniauth.origin'] || stored_location_for(resource) || root_path 
    end 
end 

Gerçek yolu yönlendirmeye buradan düzenleyebilirsiniz. Omniauth bölümünden emin değilsiniz, ancak profile_path(resource.profile)'u ekleyebilirsiniz.

Referans: https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in

1

Sen iç içe kaynakları

resources :users do 
    resource :profile 
end 

ve sonra

redirect_to [current_user, current_user.profile || current_user.build_profile] 
+0

'un altında. Merhaba - Bunu denedim, ancak şu hatayı aldım: NoMethodError (nil için tanımlanmamış metod 'profil ': NilClass): 2015-12-15T10: 33: 09.278064 + 00: 00 uygulama [web.1] : – Mel

+0

Size akım_kullanıcı (current_user == nil) olmadığınızı söyler. Tanımlanmışsa @user kullanın. –

+0

Merhaba Alexei. Ben kullanırım. Current_user yardımcım var. Ayrıca, yöntem profil söylediği zaman, kullanıcı hakkında konuştuğundan emin misiniz? – Mel

İlgili konular