2014-12-07 89 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