結合テーブルを介して has_many から has_many への関係を持つ 2 つのモデルがあります。
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 を使用してみましたが、オーサリングのためにデータベースに位置列を追加しましたが、成功しませんでした。