我有两个模型,通过连接表具有has_many到has_many的关系。
class Article < ActiveRecord::Base
has_many :authorings, -> { order(:position) }, :dependent => :destroy
has_many :authors, through: :authorings
end
class Author < ActiveRecord::Base
has_many :authorings, -> { order(:position) }
has_many :articles, through: :authorings
end
class Authoring < ActiveRecord::Base
belongs_to :author
belongs_to :article
acts_as_list :scope => :author
end
数组的getter和setter方法
def author_list
self.authors.collect do |author|
author.name
end.join(', ')
end
def author_list=(author_array)
author_names = author_array.collect { |i|
i.strip.split.each do |j|
j.capitalize
end.join(' ') }.uniq
new_or_found_authors = author_names.collect { |name| Author.find_or_create_by(name: name) }
self.authors = new_or_found_authors
end
我想维护保存到模型的作者列表的顺序。也就是说,我希望能够更改并重新排序author_list,并按顺序检索视图。我想改变它['foo','bar']或['bar','foo']。我怎么能这样做?
作为一个注释,我尝试使用acts_as_list并在数据库中添加了一个位置列以进行创作,但没有成功。
答案 0 :(得分:0)
您需要为每位作者提供一个位置属性。
然后,您可以生成已排序的activerecord数组并获取名称属性
authorlist = Author.order(:position).pluck(:name)
我没有看到你是如何改变位置属性的,我猜你在前端需要一些js才能做到这一点。