例如有沒有辦法做這樣的事情?
# IN CONTROLLER
if Tweet.find(params[:id])
@tweet = this
# instead of writing
# @tweet = Tweet.find(params[:id])
else
@tweet = Tweet.new(tweet_params)
end
例如有沒有辦法做這樣的事情?
# IN CONTROLLER
if Tweet.find(params[:id])
@tweet = this
# instead of writing
# @tweet = Tweet.find(params[:id])
else
@tweet = Tweet.new(tweet_params)
end
@tweet = Tweet.find_by(id: params[:id]) || Tweet.new(tweet_params)
find_by
將返回nil
,如果沒有被發現的記錄。如果params[:id]
爲零,find_by
也將返回nil
。
你必須鳴叫分配給一個變量:
if @tweet = Tweet.find(params[:id])
@tweet.method
else
@tweet = Tweet.new(tweet_params)
end
可以是一行:
@tweet = Tweet.find_by(id: params[:id]) || Tweet.new(tweet_params)
並非如此。到唐迪邁克爾間質的回答另一種方法是捕獲異常:
def show
@tweet = Tweet.find(params[:id])
rescue ActiveRecord::RecordNotFound
@tweet = Tweet.new(tweet_params)
end
或用少許間接:
def show
@tweet = find_or_new_tweet
end
private
def find_or_new_tweet # or whatever
@tweet = Tweet.find(params[:id])
rescue ActiveRecord::RecordNotFound
@tweet = Tweet.new(tweet_params)
end
更好:'before_action:find_or_new_tweet,只:[:show]' – tadman
事實上,'find'提出如果沒有找到記錄異常,所以'別人'永遠不會執行...... –