2016-10-27 4 views
0

現在、人が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を閲覧すること

+0

ユーザーとチャレンジの間には「has_many」関係はありますか? – mysmallidea

+0

これはいつまでも動作しますか、一度だけあなたが最後のチャレンジに遭遇しましたか? –

+0

'@ user.challenges.where( 'id>?'、@ challenge.id).first'は次の高いIDでチャレンジを返すべきです。ユーザーには多くの課題があります。 – Stefan

答えて

1

あなたがチャレンジの日付や他の属性を比較した方が良いと思うチャレンジ。例:

#next challenge 
user.challenges.where('challenge_date > ?', challenge_date).order('challenge_date ASC').first 

#previous challenge 
user.challenges.where('challenge_date < ?', challenge_date).order('challenge_date ASC').first 
+0

これは素晴らしいです!ありがとうございました!私は挑戦のために 'deadline'と' date_started'の2つの別々の日付カテゴリを使います。あなたは私が一緒にメッシングをすることで注文できる方法を知っていますか? –

関連する問題