![](/img/trans.png)
[英]How do I display select field values rather than their associated stored integers in ruby on rails?
[英]How do I select the name field in both this and an associated record in rails?
我有兩個模型,“事物”和“類別”,定義如下:
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作為數據存儲。
您可以加入並排序:
Thing.joins(:comment).order('things.name, categories.name')
然后取下這些名稱:
Thing.joins(:comment).order('things.name, categories.name').pluck('things.name', 'categories.name')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.