【问题标题】:Maintain order of saved attributes list for model维护模型保存属性列表的顺序
【发布时间】:2016-01-12 19:12:12
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 attributes rubygems acts-as-list


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2012-11-06
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      相关资源
      最近更新 更多