如何选择此栏中的名称字段以及rails中的相关记录?

时间:2015-02-04 06:48:39

标签: ruby-on-rails postgresql activerecord

我有两个模型,“Thing”和“Category”,定义如下:

class Thing < ActiveRecord::Base
  belongs_to :category

  scope :category_name, lambda { |name| joins(:category).where("name in (?)", name) }

  # need to order by category and thing name eventually
  scope :order_alphabetically, ->{ order("name")}

end

class Category < ActiveRecord::Base
  has_many :thing
end

,这些的架构如下:

ActiveRecord::Schema.define(version: 20150120222942) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "things", force: :cascade do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "name"
    t.text     "state",        default: "active"
    t.boolean  "enabled",      default: true
    t.integer  "category_id"
  end

  create_table "categories", force: :cascade do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "name"
    t.text     "description"
  end

我希望能够做两件事: a)按事物名称和类别名称对事物进行排序。 b)只选择对(thing.name,category.name)(可能使用相同的排序顺序)。

哦,我正在使用postgresql作为数据存储区,如果这有所不同。

1 个答案:

答案 0 :(得分:2)

您可以加入并排序:

Thing.joins(:comment).order('things.name, categories.name')

然后采摘这些名字:

Thing.joins(:comment).order('things.name, categories.name').pluck('things.name', 'categories.name')