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

用户资料

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 !@userprofile.nil? then
   @userprofile
 else
   @userprofile = Userprofile.new
 end
end

未定义的方法 `userprofiles' 用于#

我试过find没有更好的结果。

4

3 回答 3

5

您以错误的方式调用用户配置文件。你必须这样称呼它

@userprofile = current_user.userprofile

对于 if else 块,有如下更好的解决方案。

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

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

于 2012-11-21T05:14:34.247 回答
2

user 和 userprofile 具有一对一的关系,因此

@userprofile = current_user.userprofile

通过使用它,您可以获得 current_user 的用户配置文件

现在你的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

we use build_userprofile because it's one-to-one relation. but suppose if it's has_many relationship then we use userprofiles_build

于 2012-11-21T05:34:01.937 回答
1

As the other answers point out, you don't need the .all.where(:user_id => current_user.uid). The point of making these named associations is that rails can automatically handle looking up all the database id's.

That's also why using the build_userprofile method is a good idea, because it automatically links the new userprofile to current_user. Note that method does not automatically save the newly created record though, so make sure you call save:

@userprofile = current_user.build_userprofile
@userprofile.save
于 2012-11-21T07:13:44.407 回答