我有两个模型通过连接表具有 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 并在数据库中添加了一个位置列以进行创作,但没有成功。