2014-02-25 33 views
0

我創建一個用戶使用omniauth寶石(這是工作),但user創建後,我也想在profile表中創建一個記錄(但只有當創建一個user時)。Rails - 如何訪問父級模型中的類?

我決定在user模型中使用回調來做到這一點。

然而,執行後的回調,它打我create_profile方法,我碰到關於在user模型的方法錯誤:

undefined method `facebook' for #<Hash:0x007fdf16858200> 

即使我通過用戶:自我配置文件模型,我無法訪問它的方法。

User.rb

class User < ActiveRecord::Base 


    has_one :profile 
    has_many :pins 
    has_many :replies, through: :pins 


    after_create :build_profile 


    def self.from_omniauth(auth) 

     where(auth.slice(:provider, :provider_id)).first_or_initialize.tap do |user| 

      user.provider = auth.provider 
      user.provider_id = auth.uid 
      user.oauth_token = auth.credentials.token 
      user.oauth_expires_at = Time.at(auth.credentials.expires_at) 
      user.save 

     end 

    end 


    def build_profile 

     Profile.create_profile(user: self) 

    end 


    def facebook 

     @facebook ||= Koala::Facebook::API.new(oauth_token) 

    end 


end 

Profile.rb

class Profile < ActiveRecord::Base 


    belongs_to :user 


    def self.create_profile(user) 

       # undefined method `facebook' for #<Hash:0x007fdf16858200> for this line. 
     user.facebook.inspect 

    end 

end 

我是新來的Ruby和Rails ......所以,請多多包涵!

我欣賞你看着這個,告訴我我哪裏出錯了。

謝謝, 邁克爾。

PS - 看起來user.inspect返回用戶在我的profile.rb模型中的結果......但我試圖訪問該用戶類的方法。

+0

我沒有顯示該行,它是一個讀取:'user.facebook.inspect'。它拋出錯誤,'臉譜'是一個未定義的方法。 –

+0

啊,我看到了。抱歉。 – lurker

回答

3

您的建造輪廓的方法應該在self票代替。如果哈希user: self

def build_profile 
    Profile.create_profile(self) 
end 

build_<has_one_association>由軌道提供。

你可以做

user.build_profile #this will return a profile object with user_id set 

如果你想建立關聯的對象,而不是做

profile = Profile.new(:user_id => user.id) 

你可以做

profile = user.build_profile 

以上會自動初始化配置文件對象並設置user_id。 在你的情況下,你覆蓋了由rails提供的build_profile方法

+0

你對'self'正確,而不是傳遞用戶:hash的散列。它現在按預期工作!謝謝。你能否在第二項建議中進一步澄清?我想了解更多。 –

+0

對'build_ +1不錯。 – Stenerson

+0

任何人都可以向我解釋更多關於如何使用這個build_ 的想法嗎? –

相關問題