簡體   English   中英

Rails-如何訪問父模型中的類?

[英]Rails - How do I access a class in the parent model?

我正在使用omniauth gem創建用戶(正在運行),但是在創建user之后,我也想在profile表中創建一條記錄(但僅限於創建user時)。

我決定在user模型中使用回調來執行此操作。

但是,在執行回調並擊中了我的create_profile方法之后,我遇到了與user模型中的方法有關的錯誤:

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

即使我將user:self傳遞給配置文件模型,也無法訪問其上的方法。

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模型中返回了用戶的結果...但是我正嘗試訪問該用戶類上的方法。

如果散列user: self則您的構建配置文件方法應傳遞self而不是

def build_profile
  Profile.create_profile(self)
end

同樣, build_<has_one_association>提供了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 就您而言,您將覆蓋build_profile提供的build_profile方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM