[英]Is there an equivalent to a jQuery $(this) in Rails controller?
例如,有没有办法做这样的事情?
# 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]
为nil,则find_by
也将返回nil
。
没那么多。 Dondi Michael Stroma的答案的另一种选择是捕获异常:
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
您必须将推文分配给变量:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.