0

結合テーブルを介して 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 を使用してみましたが、オーサリングのためにデータベースに位置列を追加しましたが、成功しませんでした。

4

1 に答える 1

0

著者ごとに位置属性が必要です。

次に、ソートされたアクティブレコード配列を生成し、名前属性を取得できます

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

position 属性をどのように変更しているのかわかりません。それを行うには、フロントエンドに何らかの js が必要だと思います。

于 2016-04-18T04:03:42.853 に答える