現在、人がlink_to
をクリックすると、前回または次のチャレンジに持ち込まれます。次と前の@ユーザーのオブジェクトですか?
しかし、どのようにlink_to
は@user
の挑戦だけが含まれていますか?
ビュー
<% if @challenge.previous %>
<%= link_to 'Prev', challenge_path(@challenge.previous), class: "footer-left", style: "color: white; font-style: normal;" %>
<% else %>
<%= link_to 'Home', root_url, class: "footer-left" %>
<% end %>
<% if @challenge.next %>
<%= link_to 'Next', challenge_path(@challenge.next), class: "footer-right" %>
<% else %>
<%= link_to 'Home', root_url, class: "footer-right" %>
<% end %>
モデル
def next
Challenge.where("id > ?", id).first # I get nil error for... Challenge.find_by(user_id: @user.id).where("id > ?", id).first
end
def previous
Challenge.where("id < ?", id).last # I get nil error for... Challenge.find_by(user_id: @user.id).where("id > ?", id).last
end
私は@user
がモデルでは動作しません知っているが、私はちょうど取得しようとするための一例として、それを使用しています彼らが挑戦しているUser
。
class User < ApplicationRecord
has_many :challenges
end
class Challenge < ApplicationRecord
belongs_to :user
end
だからあなたの方法は次のようになります。:
class Challenge < ApplicationRecord
belongs_to :user
#don't use just "next" because it's a ruby reserved keyword that you can use to skip to the next iteration of a loop
def next_user_challenge
user.challenges.where('id > ?', id).first
end
def previous_user_challenge
user.challenges.where('id > ?', id).last
end
end
そしてもう一点、次および前を閲覧するために、私はあなたのモデルがどのように見えることを仮定しているユーザーchalengesを閲覧すること
ユーザーとチャレンジの間には「has_many」関係はありますか? – mysmallidea
これはいつまでも動作しますか、一度だけあなたが最後のチャレンジに遭遇しましたか? –
'@ user.challenges.where( 'id>?'、@ challenge.id).first'は次の高いIDでチャレンジを返すべきです。ユーザーには多くの課題があります。 – Stefan