我使用的是simple_form grouped_select
,但我没有得到我想要的输出。
模型
class PartnerName < ApplicationRecord
has_many :urls, dependent: :destroy
end
#<PartnerName id: 1, name: "technology", app_name: "test">
#<PartnerName id: 2, name: "technology", app_name: "user">
class Url < ApplicationRecord
belongs_to :network_partner_name
end
#<Url id: 1, partner_name_id: 1, name: "abc.org">
#<Url id: 2, partner_name_id: 1, name: "qwe.org">
#<Url id: 3, partner_name_id: 2, name: "123.org">
#<Url id: 4, partner_name_id: 2, name: "345.org">
查看文件
= simple_form_for(:query, method: :post) do |f|
= f.error_notification
.form-row
.col-auto
= f.input :network_partner_name_id, collection: PartnerName.order(:name),
include_blank: false
.form-row
.col-auto
= f.input :url_id, collection: PartnerName.order(:name).includes(:urls),
as: :grouped_select,
group_method: :urls,
include_blank: false
输出
我得到的结果如上所述。
对于PartnerName
<option value="1">technology</option>
<option value="2">technology</option>
For Url
<optgroup label="technology">
<option value="1">abc.org</option>
<option value="2">qwe.org</option>
</optgroup>
<optgroup label="technology">
<option value="3">123.org</option>
<option value="4">456.org</option>
</optgroup>
但我希望通过ParnerName的名称和ParnerName的app_name属性获得如下所示的输出。我该怎么做?
对于PartnerName
<option value="1">technology - test</option>
<option value="2">technology - user</option>
For Url
<optgroup label="technology - test">
<option value="1">abc.org</option>
<option value="2">qwe.org</option>
</optgroup>
<optgroup label="technology - user">
<option value="3">123.org</option>
<option value="4">456.org</option>
</optgroup>
谢谢。
答案 0 :(得分:1)
您可以为PartnerName
class PartnerName < ApplicationRecord
has_many :urls, dependent: :destroy
def label_collection
"#{name} - #{app_name}"
end
end
并将其与label_method
和group_label_method
simple_form助手一起使用:
= simple_form_for(:query, method: :post) do |f|
= f.error_notification
.form-row
.col-auto
= f.input : network_partner_name_id, collection: PartnerName.order(:name),
label_method: :label_collection,
include_blank: false
.form-row
.col-auto
= f.input :url_id, collection: PartnerName.order(:name).includes(:urls),
as: :grouped_select,
group_method: :urls,
group_label_method: :label_collection,
include_blank: false