จัดเรียงรายการหัวข้อตามวันที่สร้างของโพสต์ล่าสุด

การสร้างแอปฟอรั่ม

class Topic < ActiveRecord::Base
  belongs_to :user
  belongs_to :board
  has_many :posts, :inverse_of => :topic
end

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic, :inverse_of => :posts
end

เมื่อดูบอร์ด ฉันต้องการให้รายการหัวข้อเรียงลำดับตามหัวข้อโพสต์ล่าสุดที่สร้าง_ณ วันที่ แต่ฉันไม่สามารถหาวิธีเขียนสิ่งนี้ในลักษณะที่สามารถเข้าใจได้โดยเมธอด order()

เป็นการดีที่มันจะง่ายแบบนี้

@topics = @board.topics.order("topic.posts.last.created_at")

ทุกสิ่งที่ฉันเขียนส่งคืนข้อผิดพลาดเกี่ยวกับคอลัมน์ที่ไม่มีอยู่

สิ่งสำคัญอย่างหนึ่งที่ควรทราบก็คือ @topics นี้จะถูกป้อนเข้าในการแบ่งหน้า ดังนั้นฉันไม่สามารถแยกผลลัพธ์ของ @board.topics ออกคำสั่งด้วยตัวเองแล้วจึงแบ่งหน้าได้เนื่องจากการแบ่งหน้าต้องใช้คอลเลกชันประเภทเฉพาะ


person Adam    schedule 15.08.2014    source แหล่งที่มา


คำตอบ (1)


  1. แนบข้อความแสดงข้อผิดพลาดเสมอ
  2. ใช้การเรียงลำดับ:

    @topics = @board.topics.sort{|t| t.posts.last.created_at}

person Easy peasy    schedule 15.08.2014
comment
วิธีการของคุณส่งคืนข้อผิดพลาด: CACHE (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."topic_id" = ? ORDER BY "posts"."id" DESC LIMIT 1 [["topic_id", 3]] *** ArgumentError Exception: comparison of ActiveSupport::TimeWithZone with 0 failed นอกจากนี้ ฉันได้ลองทำเช่นนี้แล้ว แต่ไม่ได้ผล เนื่องจากเมื่อเรียงลำดับแล้ว การแบ่งหน้าในรายการที่เรียงลำดับแล้วทำให้เกิดข้อผิดพลาดต่อไปนี้: *** NoMethodError Exception: undefined method paginate' สำหรับ #‹Array:0xb571f63c›` - person Adam; 16.08.2014
comment
เนื่องจากข้อผิดพลาดนี้ ให้ลองเพิ่ม need 'will_paginate/array' ในคอนโทรลเลอร์ของคุณ - person Easy peasy; 16.08.2014