2012-11-21 54 views
0

我有这两款车型用户如何在一对一关系中查找对象模型?

class User < ActiveRecord::Base 
attr_accessible :name, :provider, :uid 

# This is a class method, callable from SessionsController 
# hence the "User." 
def User.create_with_omniauth(auth) 
    user = User.new() 
    user.provider = auth["provider"] 
    user.uid = auth["uid"] 
    user.name = auth["info"]["name"] 
    user.save 
    return user  
    end 

has_one :userprofile 
end 

USERPROFILE

class Userprofile < ActiveRecord::Base 
    belongs_to :user 
    attr_accessible :age, :fname, :gender, :lname, :photo_url 
end 

我想检查是否有与用户相关的一个USERPROFILE对象。如果有,显示它。否则,请创建一个新的。

我正在尝试这个,并得到一个错误。

def show 
@userprofile = current_user.userprofiles.all.where(:user_id => current_user.uid) 
if [email protected]? then 
    @userprofile 
else 
    @userprofile = Userprofile.new 
end 
end 

未定义的方法`的UserProfiles'为#

我已经试过找到没有更好的结果。

回答

2

用户和用户配置文件有一个一对一的关系,以便

@userprofile = current_user.userprofile 

利用这一点,你可以得到CURRENT_USER的USERPROFILE

现在您show方法看起来像

def show 
if current_user.userprofile.present? 
    @userprofile = current_user.userprofile 
else 
    @userprofile = current_user.build_userprofile 
end 
end 

更新:为什么要建立

http://edgeguides.rubyonrails.org/association_basics.html#has-one-association-reference

我们使用build_userprofile,因为它是one-to-one的关系。但假设它是否has_many关系,那么我们使用userprofiles_build

+0

它正在工作。我只是想知道我该如何猜测build_userprofile方法的存在。大声笑!任何链接? – Richard77

+0

看到更新:为什么建立 - 并看到链接 –

+0

更好的链接将http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference,因为有很多关于我们不知道的关联的东西。 –

5

您正在以错误的方式调用userprofile。你要这样称呼它

@userprofile = current_user.userprofile

,为的if else块有一个更好的解决方案如下。

@userprofile = current_user.userprofile || current_user.userprofile.new 

这将初始化用户配置文件,如果它没有创建。

1

正如其他答案指出的,你不需要.all.where(:user_id => current_user.uid)。使这些命名关联的要点是,rails可以自动处理查找所有数据库ID。

这也是为什么使用build_userprofile方法是一个好主意,因为它会自动将新的userprofile链接到current_user。请注意,该方法不会自动保存新创建的记录,因此请确保您致电保存:

@userprofile = current_user.build_userprofile 
@userprofile.save 
相关问题