Ric*_*d77 0 activerecord ruby-on-rails
我有这两个型号的用户:
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
Run Code Online (Sandbox Code Playgroud)
和userprofile:
class Userprofile < ActiveRecord::Base
belongs_to :user
attr_accessible :age, :fname, :gender, :lname, :photo_url
end
Run Code Online (Sandbox Code Playgroud)
我想检查是否有与用户关联的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
Run Code Online (Sandbox Code Playgroud)
用于#的未定义方法`userprofiles'
我试图找到没有更好的结果.
您以错误的方式调用userprofile.你必须称之为
@userprofile = current_user.userprofile
对于if else块,有一个更好的解决方案如下.
@userprofile = current_user.userprofile || current_user.userprofile.new
Run Code Online (Sandbox Code Playgroud)
如果没有创建用户配置文件,这将初始化.