[英]Rails - How do I access a class in the parent model?
I'm creating a user using omniauth gem (which is working), but after the user
is created, I'd like to create a record in the profile
table too (but only when a user
is created). 我正在使用omniauth gem创建用户(正在运行),但是在创建
user
之后,我也想在profile
表中创建一条记录(但仅限于创建user
时)。
I decided to use a callback in the user
model to do this. 我决定在
user
模型中使用回调来执行此操作。
However, after the callback is performed and it hits my create_profile
method, I run into an error regarding a method in the user
model: 但是,在执行回调并击中了我的
create_profile
方法之后,我遇到了与user
模型中的方法有关的错误:
undefined method `facebook' for #<Hash:0x007fdf16858200>
Even though I'm passing user: self to the profile model, I am not able to access methods on it. 即使我将user:self传递给配置文件模型,也无法访问其上的方法。
User.rb 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 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
I'm new to Ruby and Rails...so, please bear with me! 我是Ruby和Rails的新手...所以,请多多包涵!
I appreciate you looking this over and telling me where I'm going wrong. 感谢您仔细查看并告诉我我要去哪里错了。
Thanks, Michael. 谢谢,迈克尔。
PS - It seems user.inspect
returns the result of a user in my profile.rb
model...but I am trying to access the method on that user class. PS-似乎
user.inspect
在我的profile.rb
模型中返回了用户的结果...但是我正尝试访问该用户类上的方法。
your build profile method should pass in self
instead if the hash user: self
如果散列
user: self
则您的构建配置文件方法应传递self
而不是
def build_profile
Profile.create_profile(self)
end
also, build_<has_one_association>
is provided by rails. 同样,
build_<has_one_association>
提供了build_<has_one_association>
。
you can just do 你可以做
user.build_profile #this will return a profile object with user_id set
If you want to build the associated object, instead of doing 如果要构建关联的对象,而不是
profile = Profile.new(:user_id => user.id)
You could do 你可以做
profile = user.build_profile
The above will automatically initialize the profile object and set the user_id
. 上面的代码将自动初始化配置文件对象并设置
user_id
。 In your case, you are overriding the build_profile
method provided by rails 就您而言,您将覆盖
build_profile
提供的build_profile
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.