开发者

How to add Previous / Next links in show view?

开发者 https://www.devze.com 2023-02-12 08:31 出处:网络
I\'m trying to add Prevous/Next links in my show view. Here is the model: Position belongs_to :skill Skill

I'm trying to add Prevous/Next links in my show view. Here is the model:

Position
belongs_to :skill

Skill
has_many :positions, :order => 'salary desc, id desc'

position/show view:

<%= link_to("Previous", @position.previous) if @position.previous %>
<%= link_to("Next", @positi开发者_如何学Con.next) if @position.next %>

position.rb (new lines added for readibility)

def next
  self.class
  .where("skill_id = ? AND salary <= ? AND id < ?", skill_id, salary, id)
  .order("salary desc, id desc").first
end

This doesn't do what I want. Records should be ordered first by salary, and than by id.

I think will_paginate won't help me because it's only for collections (won't work in the show view)


You should look at the paginate gem it does all the logic for you and creates your view links as well https://github.com/mislav/will_paginate


Ok, try looking at this gem: http://metautonomo.us/projects/metawhere/

It seems the issue is your SQL mojo isn't quite on target, but as I have absolutely no SQL mojo I don't know why your approach isn't working.

Metawhere lets you use very precise ruby code for generating complex SQL queries. From the project homepage it gives this example of complex order clauses:

Article.order(
    :title.desc,
    :comments => [:created_at.asc, :updated_at]
  ).joins(:comments)

So, I think if you were using metawhere you could simply add this to your where clause:

... :order => [:id.desc, :salary.desc] ...

or chain it on as a .order().

I hope that helps!


I found the solution :) It's rather long, but it works:

where("skill_id = ? AND salary = ? AND id < ?
       OR 
       skill_id = ? AND salary < ?",
       skill_id, salary, id, skill_id, salary
     )
     .order("salary desc, id desc").first
0

精彩评论

暂无评论...
验证码 换一张
取 消