AnthonyGalli.com AnthonyGalli.com - 1 month ago 12
Ruby Question

Next & previous through @user's object?

Currently if a person clicks the

link_to
they're brought to the previous or next challenge.

But how can
link_to
work where only
@user
`s challenges are included?

view

<% 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 %>


model

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


I know
@user
doesn't work in the model, but I'm just using it as an example for trying to get the
User
whose challenges they belong to.

Answer

To browse the user chalenges i'm assuming that your models look like:

class User < ApplicationRecord
  has_many :challenges
end

class Challenge < ApplicationRecord
  belongs_to :user
end

So your method should be:

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

And one more point, to browse the next and previous challenges i think that would be better if you compare the challenge's date or some other attribute. Example:

#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
Comments