railsのactiverecordでlastの一つ手前を取得したい。secondの逆をやりたい。
$ rails c # ユーザー取得 u = User.find(1) # ユーザーのtweetを取得したい u.tweets.content # ユーザーのtweetの最新を取得したい u.tweets.last.content # ユーザーのtweetの最初のを取得したい u.tweets.first.content # ユーザーのtweetの最初2個目を取得したい u.tweets.second.content # ユーザーのtweetの最新の一つ前を取得したい u.tweets.last(2)[0].content
u.tweets.last(2).content
だと構文エラーになる罠があるので注意。
u.tweets.last(2)で取得できるのは、tweetオブジェクトの配列なので、要素指定してあげないとだめ。