【问题标题】:How can I fetch the records with order by nested column?如何按嵌套列的顺序获取记录?
【发布时间】:2013-01-03 01:05:10
【问题描述】:

用户

  • has_many :communities
  • has_many :posts

社区

  • belongs_to :user
  • has_many :posts

发帖

  • belongs_to :user
  • belongs_to :community

我想在 example.com/posts 上显示所有帖子记录
但它必须按用户表中的 Post owner User's 'last_signed_in' 列进行排序。

我试过了,但这会返回错误undefined method `users' 我该如何解决?

@orders = @community.posts.user.order("last_active_at ASC")

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您不能在帖子集合上调用用户对象。

    但您可以将用户包含在您的集合中:

    @community.posts.includes(:user).order("users.last_signed_in")
    

    更多信息: http://guides.rubyonrails.org/active_record_querying.html#eager-loading-multiple-associations

    【讨论】:

    • 谢谢!但是 itt 虽然返回了这个错误。 Mysql2::Error: Unknown column 'user.last_signed_in' in 'order clause': SELECT posts.... 实际上我在 Users 表中有“last_signed_in”
    • 对不起,我在示例代码中有错字。该表必须是“用户”而不是“用户”。我在答案中更正了它。
    猜你喜欢
    • 2020-03-03
    • 2022-01-06
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多