2014-12-07 36 views
0

這工作完全正常:軌道4創建類的方法協會

User.first.social_profiles.create! 

在另一方面,這會在social_profile但不建立兩者之間的關聯關係:

class SocialProfile < ActiveRecord::Base 

def self.create_google(auth_info) 
     # if where(provider: auth_info["provider"], uid: auth_info["uid"]).empty? 
      create! do |google| 
       google.provider = auth_info["provider"] 
       google.uid = auth_info["uid"] 
       google.image_url = auth_info["info"]["image"] 
       google.email = auth_info["info"]["email"] 
       google.access_key = auth_info["credentials"]["token"] 
       google.refresh_token = auth_info["credentials"]["refresh_token"] 
       google.expires_at = Time.at(auth_info["credentials"]["expires_at"]) 
       google.expires = auth_info["credentials"]["expires"] 

      end 
     # else 
      # where(provider: auth_info[:provider], uid: auth_info[:uid]).first 
     # end 
    end 

end 

控制檯:

2.1.2 :102 > User.first.social_profiles.create_google(...the auth hash ...) 

這裏有什麼問題?我該如何解決它?

這不工作,雖然

p = User.first.social_profiles.create_google(...the auth hash ...) 
User.first.social_profiles << p 

回答

0

的User.first實例不得意忘形到SocialProfile.create_google方法,因此創造!方法不會有用戶實例可用。 你可以通過它在自己爲它分配:

class SocialProfile < ActiveRecord::Base 
    def self.create_google(user, auth_info) 
    create! do |google| 
     google.user_id = user.id, 
     ... 
    end 
    end 
end 

而且隨着

SocialProfile.create_google(User.first, auth_info) 

叫它另外,考慮其在用戶的create_google_profile方法,這樣就可以

class User < ActiveRecord::Base 
    def create_google_profile(auth_info) 
    self.social_profiles.create(
     provider: auth_info["provider"], 
     ... 
    ) 
    end 
end 

並用

User.first.create_google_profile(auth_info) 
+0

感謝您的迴應,我意識到它不會結轉,但我不知道爲什麼。這看起來像'has_and_belongs_to_many'關聯是唯一的,因爲'has_many'不會導致這個問題? – 2014-12-07 07:08:54

+0

我一直認爲類方法不會有關聯。從未進一步探索。 沒有真正的相關性,但出於好奇,你的社交形象has_many用戶? – roob 2014-12-10 05:35:38