0

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

4

1 回答 1

0

您需要为每个作者设置一个位置属性。

然后就可以生成一个有序的activerecord数组,并获取name属性

authorlist = Author.order(:position).pluck(:name)

我没有看到你是如何改变位置属性的,我猜你需要前端的某种 js 来做到这一点。

于 2016-04-18T04:03:42.853 回答