我有一个由Active Admin管理的多态has_many到has_many关联。有两种不同的模型BlogArticle和MagazineArticles,它们通过Authoring表具有许多Authors。关联正常运行,但我必须在活动admin中创建某种输入,以便管理员指定任何单个文章的作者出现顺序。
因此,目标是使任何BlogArticle和Magazine Article都有许多具有自定义顺序的作者。
我可以使用在创作表中放置的职位属性,但如何在Active Admin中对其进行管理?
此刻,我在MagazineArticle和BlogArticle中的输入字段是:
f.input :authors,
label: "Autori",
as: :select, multiple: true,
collection: Author.all.collect {|item| [item.full_name, item.id] }
end
此“选择”将作者按作者对象(而不是创作对象)的updated_at排序。此选择来自一个名为activeadmin-addons的gem,它对我们来说很完美,但我也可以接受另一种进行方法。
模型是:
class Authoring < ApplicationRecord
belongs_to :author
belongs_to :authorable, :polymorphic => true
default_scope {order(position: :asc)}
end
class Author < ApplicationRecord
has_many :authorings
has_many :blog_articles, :through => :authorings,
:source => :authorable,
:source_type => "BlogArticle"
has_many :magazine_articles, :through => :authorings,
:source => :authorable,
:source_type => "MagazineArticle"
end
class BlogArticle < ApplicationRecord
has_many :authorings, :as => :authorable, dependent: :destroy
has_many :authors, :through => :authorings
end
class MagazineArticle < ApplicationRecord
has_many :authorings, :as => :authorable, dependent: :destroy
has_many :authors, :through => :authorings
end
及其正确添加了我需要的所有作者,但显然没有任何顺序。
我如何在Active Admin中管理创作的位置?
@blog_article.authors
或@magazine_article.authors
,应按Author
的'position'属性排序的顺序提供该文章的所有作者。您可以通过在has_many :authors
和BlogArticle
模型中按MagazineArticle
关联添加顺序来实现。
您的关联将如下所示:
has_many :authors, -> {order('authors.position')}, :through => :authorings
OR您可以在
Author
模型中定义默认范围,如下所示:default_scope { order('position desc')}