1

So I have the following code that I wanted to make a little more readable:

user = User.find_by_username(username)
user = User.new(credentials) if user.nil?

Essentially the first line is the default, the following line instantiates itself if it's not already set.

Is there a way I can clean this up a bit and get it onto a single line of code? Something like this maybe:

user = User.find_by_username(username) || User.new(credentials)

Edit

I now realize the the code I provided does exactly what I need, sorry for wasting cyberspace but feel free to suggest alternative solutions.

4

2 に答える 2

5

はい、あなたが書いたことはまさに正しい答えです。

必要に応じて、次のように書くこともできます。

user = User.find_by_username(username)
user ||= User.new(credentials)

最初の例は、最初の値が の場合にのみ 2 番目の値nilを割り当てることに注意してnilくださいfalse

EDIT:他の人が述べたように、Active Recordを使用している場合は、動的な属性ベースのファインダーを使用することもできます

user.find_or_initialize_by_username(credentials)
于 2012-10-12T22:14:11.537 に答える
3

その方が簡単です

user.find_or_create_by_name(credentials)

資格情報にはユーザー名があります

複数の属性による Rails find_or_create を参照してください。

およびhttp://api.rubyonrails.org/classes/ActiveRecord/Base.html

于 2012-10-12T22:16:24.283 に答える