使用ActiveRecord条件在相关模型中按字段排序

时间:2013-06-28 15:01:01

标签: ruby-on-rails ruby rails-activerecord

我试图通过Rails中相关模型中的字段进行排序。如果相关模型被另一个参数过滤,我研究过的所有解决方案都没有解决?

项目模型

class Item < ActiveRecord::Base
  has_many :priorities

相关型号:

class Priority < ActiveRecord::Base
  belongs_to :item

  validates :item_id, presence: true
  validates :company_id, presence: true
  validates :position, presence: true
end

我正在使用where子句检索Items:

@items = Item.where('company_id = ? and approved = ?', @company.id, true).all

我需要通过相关表格中的“位置”列进行排序。问题在于,在优先级模型中,可以列出多个公司的项目。所以这些职位取决于他们拥有哪家公司。当我显示项目时,它是针对一家公司,按公司内部的位置排序。完成此任务的正确方法是什么?任何帮助表示赞赏。

PS - 我知道acts_as_list然而发现它不太适合我的设置,所以我手动处理保存排序,同时仍然使用jquery ui sortable。

2 个答案:

答案 0 :(得分:9)

您可以使用includes方法包含构建关联,然后按顺序排序。您只需确保消除所订购字段的歧义,并且在here的热切加载中应该阅读一些内容。所以它可能是这样的:

@items = Item.includes(:priorities).where('company_id = ? and approved = ?', @company.id, true).order("priorities.position ASC")

答案 1 :(得分:1)

class Item < ActiveRecord::Base
  has_many :priorities
  belongs_to :company
  def self.approved
    where(approved: true)
  end
end

class Priority < ActiveRecord::Base
  belongs_to :item
end

class Company < ActiveRecord::Base
  has_many :items
end

@company = Company.find(params[:company_id])
@items = @company.items.joins(:priorities).approved.order(priorities: :position)

如果我理解了你的问题,我就是这样做的。它并不需要太多解释,但是如果你不确定的话就知道。

如果您想将更多内容推送到模型中,如果这是一个常见的要求,您可以调整订单的范围:

class Item < ActiveRecord::Base
  has_many :priorities
  belongs_to :company

  def self.approved
    where(approved: true)
  end

  def self.order_by_priority_position
    joins(:priorities).order(priorities: :position)
  end
end

并使用:@company.items.approved.order_by_priority_position

相关问题