Active Admin-自定义订单/从has_many到has_many多态的位置排序

问题描述 投票:0回答:1

我有一个由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中管理创作的位置?

ruby-on-rails sorting many-to-many activeadmin polymorphic-associations
1个回答
0
投票
您希望得到的结果是您致电时@blog_article.authors@magazine_article.authors,应按Author的'position'属性排序的顺序提供该文章的所有作者。

您可以通过在has_many :authorsBlogArticle模型中按MagazineArticle关联添加顺序来实现。

您的关联将如下所示:

has_many :authors, -> {order('authors.position')}, :through => :authorings

OR

您可以在Author模型中定义默认范围,如下所示:

default_scope { order('position desc')}
© www.soinside.com 2019 - 2024. All rights reserved.