0

I had managed to allow posts to be featured (admin side), but I had some problems displaying them on the index view.

Note: with sqlite works fine, but on heroku with pg, doesn't work as expected.

Note2: featured_post is a string (it has "no" or "yes", "no" by default).

My model post.rb

if Rails.env.production? scope :featured, -> { order(featured_post: :asc, created_at: :desc).limit(100) } #pg else scope :featured, -> { order(featured_post: :desc, created_at: :desc).limit(100) } #sqlite end

My controller posts_controller.rb

def index if params[:search] @posts = Post.search(params[:search]).order("created_at DESC").paginate(page: params[:page], :per_page => 20) else
@posts = Post.all.featured end end

With SQLite the "featured posts" are shown on top, and ordered by DESC no matter if the post is older. So it works as expected, everything OK. For example:

  1. Title One : 21.12.2014 featured
  2. Title Two : 09.22.2008 featured
  3. Title three : 02.01.2015 (today)
  4. Title four : 01.01.2015 (yesterday)

featured is on top and ordered by date (recent featured first).

With PostgreSQL on Heroku, it gives me some problems. For example:

  1. Title One : 02.01.2015 (today) not featured (but it show on top)
  2. Title Two : 21.12.2014 featured
  3. Title Three : 09.22.2008 featured
  4. Title Four : 02.01.2015 (today)
  5. Title Five : 01.01.2015 (yesterday)

featured is not on top when new post (default "no" featured) is created. The ordering by date is ok, as you see, but it "doesn't" stay on top, when a new post is created.

Had to say that I tried DESC and DESC or ASC and ASC or DESC and ASC, etc on heroku postgresql, with no success.

Any suggestions, ideas are much welcomed. Thanks in advance!!

4

1 回答 1

0

经过半天的搜索并试图使精选帖子保持在最前面并按最近排序,我设法找到了一个解决方案(这不是最好的,但它是一个“暂时的解决方案”。这是我所做的:

模型post.rb

scope :featured, -> { where(featured_post: 'yes').order(created_at: :desc) } scope :unfeatured, -> { where(featured_post: 'no').order(created_at: :desc) }

控制器 posts_controller.rb

@posts_featured = Post.all.featured @posts_unfeatured = Post.all.unfeatured

查看 index.html.erb

精选

<% @posts_featured.each do |post| %> <header><h2 class="title"><%= link_to post.title, html_css_show_path(post) %></h2></header> <div><%= post.body %></div> <% end %>

无特色

<% @posts_unfeatured.each do |post| %> <header><h2 class="title"><%= link_to post.title, html_css_show_path(post) %></h2></header> <div><%= post.body %></div> <% end %>

这就是诀窍。同样,这不是一个很好的解决方案,但它让我暂时摆脱了这个问题。希望可以帮助别人。顺便说一句,我在ruby​​ 2.1.4上使用rails 4.1.8。干杯!

于 2015-01-03T01:58:36.430 回答