0

私はこれらの2つのモデルuserを持っています:

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 を間違った方法で呼び出しています。あなたはそれを次のように呼び出す必要があります

@userprofile = current_user.userprofile

if else ブロックについては、次のようなより良い解決策があります。

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

ユーザープロファイルが作成されていない場合、これによりユーザープロファイルが初期化されます。

于 2012-11-21T05:14:34.247 に答える
2

user と userprofile は 1 対 1 の関係にあるため、

@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

build_userprofile関係があるので使いますone-to-one。しかし、それが has_many 関係である場合、使用するとしますuserprofiles_build

于 2012-11-21T05:34:01.937 に答える
1

他の回答が指摘しているように、は必要ありません.all.where(:user_id => current_user.uid)。これらの名前付き関連付けを作成するポイントは、railsがすべてのデータベースIDの検索を自動的に処理できることです。

これは、build_userprofileメソッドを使用することをお勧めする理由でもあります。これは、新しいuserprofileをcurrent_userに自動的にリンクするためです。ただし、メソッドは新しく作成されたレコードを自動的に保存しないことに注意してください。そのため、必ずsaveを呼び出してください。

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