有4种型号。(时尚,时尚内衣,内衣,品牌)。每个用户都可以从时尚形式中选择自己的风格。时尚形式有各种项目的下拉盒,如牛仔裤和袜子。我想重新排列项目按字母顺序在Drop框中按品牌分类,所以我使用了范围。
#### Underwear dropbox
Adidas
adidas underwear 1
adidas underwear 2
NIKE
NIKE underwear 1
NIKE underwear 2
NIKE underwear 3
它适用于范围,但现在我收到警告,你应该包括范围。 在下面的代码中,打开Fashions / new.html会给我一个警告“Please Include UnderwearNameAsc”。 我研究过各种各样的东西并尝试过,但在所有使用儿童模型的情况下,我找不到解决的线索。
### Fashion model
has_one :fashion_underwear
accepts_nested_attributes_for :fashion_underwear
### FashionUnderwear model(Intermediate table)
belongs_to :fashion
belongs_to :underwear
### Underwear model
has_many :fashion_underwears
belongs_to :brand
scope :UnderwearNameAsc, -> { order(UnderwearName: :asc) }
### Brand model
has_many :underwear
has_many :UnderwearNameAsc, -> { order(UnderwearName: :asc) }, class_name: 'Underwear'
### Fashions.controller
def new
@fashion = Fashion.new
@fashion.build_fashion_underwear
@brand = Brand.includes(:fashion_underwears).joins(:fashion_underwears).order(brand_name: :asc)
end
### Fashion/new.html
= simple_form_for(@fashion) do |f|
= f.simple_fields_for :fashion_underwear do |p|
= p.input :underwear_id, collection: @brand, as: :grouped_select, group_method: :UnderwearNameAsc, group_label_method: :brand_name, label_method: :UnderwearName
答案 0 :(得分:0)
子弹指出你有n+1 query problem。它建议您通过添加includes
来解决问题,从而更改Brand模型中的has_many关联,如下所示:
has_many :UnderwearNameAsc, -> { includes(:underwear).order(UnderwearName: :asc) }, class_name: 'Underwear'
当你在这里时,你真的应该在standard Ruby style中将范围和方法的名称更改为snake_case。否则Ruby会认为这些方法和范围是常量。
此外,我只会为您返回的内容命名范围,而不是该模型上的单个属性。最后,我要单独使用一个作用域,并在需要对资源进行排序时显式调用它。
has_many :underwear # Or has_many :underwears if Rails interprets the plural that way
scope :sorted, -> { includes(:underwear).order(underwear: {name: :asc} }
然后你可以这样做:
Brand.all # Returns unsorted records
Brand.all.sorted # Returns records sorted by underwear.name