我正在使用Rails 5和activeadmin gem构建一个电子商务网站来管理我的仪表板。我有一个多对一关系的产品和类别模型。
class Product < ApplicationRecord
before_destroy :not_referenced_by_any_line_item
belongs_to :category
has_many :line_items, dependent: :destroy
has_many :reviews, dependent: :destroy
def self.search(search)
all.where("lower(title) LIKE :search", search: "%#{search}%")
end
private
def not_referenced_by_any_line_item
unless line_items.empty?
errors.add(:base, "line items present")
throw :abort
end
end
end
class Category < ApplicationRecord
has_many :products, dependent: :destroy
def self.search(search)
all.where("lower(category_name) LIKE :search", search: "%#{search}%")
end
end
然后我将模型注册到如下的activeadmin仪表板中
ActiveAdmin.register Product do
permit_params :title, :description, :availability,
:price, :photo_link, :category_id, :advert, :pictureOne,
:pictureTwo, :pictureThree
end
ActiveAdmin.register Category do
permit_params :category_name, :photos
end
我现在可以在创建产品时在项目表单上选择产品类别,但是问题是,不是类别名称或要在项目类别表单输入字段上显示的任何其他字段,因此您可以准确地知道要选择的类别,则会显示一个摘要,使您很难知道您选择的是哪个类别。显示产品类别输入表单字段的下拉列表:
ActiveAdmin的默认功能是,在确定要呈现为记录的标识符时,在给定模型上查找name
字段。如果模型中没有name
字段,则ActiveAdmin除了可以向您显示该记录在内存中的位置的乱七八糟的内容外,不会通过其他方式让您处理正在处理的记录。如果您在控制台中执行了Category.first.to_s
,则将得到相同的字符串。
为了使ActiveAdmin能够识别名称,您必须覆盖它为您创建的默认编辑表单,以便您可以自定义选择标签。
您将要编辑的所有字段添加到表单中。当您添加类别的输入时,可以指定要将该字段作为选择,然后可以自定义选择的标签,如下所示:
# app/admin/product.rb
ActiveAdmin.register Product do
permit_params :title, :description, :availability,
:price, :photo_link, :category_id, :advert, :pictureOne,
:pictureTwo, :pictureThree
form do |f|
f.inputs do
# Add a form input for the category
#
# This approach also allows you to specify which categories you
# allow to be selected, in the "collection" attribute.
#
# Inside the "map" call, you have the proc return an array with the first item
# in the array being the name of the category (the label for the select)
# and the second item being the category's ID (the select's value)
f.input :category_id, label: 'Category', as: :select, collection: Category.all.map{ |c| [c.category_name, c.id]}
# Then add other inputs
f.input :title
f.input :description
f.input :availability
# ...
# (Add f.input for the rest of your fields)
end
f.actions
end
end
当您需要在ActiveAdmin的其他位置将名称呈现为类别时,将采用类似的方法。
如果不是很麻烦,最好将类别模型上的category_name
重命名为name
。这样,您与ActiveAdmin的争斗就会减少很多,并且不需要进行如此多的自定义。