Richlewis
Richlewis

Reputation: 15384

Previous and next links when changing to_param

I am creating next and previous links, but have run into a spot of bother, as I have changed the way my url looks by modifying the to_param method:

 def slug
  name.downcase.gsub(" ", "-")  
 end

 # URL will now show /id-name
 def to_param
  "#{self.id}-#{slug}"
 end

So my method to get the previous link looks like:

def previous_animal
 self.class.first(:conditions => ["id-name < ?", "what-to-put-here"], :order => "created_at desc")
end

Am I right in thinking that if I was just using an id it would be:

def previous_animal
 self.class.first(:conditions => ["id < ?", id], :order => "created_at desc")
end

How can I pass the new id format?

Edit

As pointed out by D-side, database lookup is unchanged, so when trying the following I am getting an error:

def previous_animal
 self.class.first(:conditions => ["id < ?", id], :order => "created_at desc")
end

View

<%= link_to(@animal.previous_animal) %>

Error:

invalid value for Integer(): "{:conditions=>[\"id < ?\""

so the link_to is expecting an integer but what is being passed looks something like this:

{"id"=>"27-clawd"}

Upvotes: 0

Views: 81

Answers (2)

mahemoff
mahemoff

Reputation: 46489

You're relying on id and created_at being in sync, ie assuming a model created after another model will always have a higher ID. It's true in general, but depends on the database and a risky assumption (the ID or created_at can be changed manually, for example).

So I would do something like:

def previous_animal
  animal = self.class.order('created_at desc').where('created_at < ?', self.created_at)
  animal.first if animal
end

Upvotes: 1

j-dexx
j-dexx

Reputation: 10416

You've tagged this as rails 4 but seem to be using rails 2 syntax.

Does this work?

def previous_animal
  self.class.where("id < ?", id).order(created_at: :desc).first
end

Upvotes: 2

Related Questions