在rails_admin中使用orderable获取rails 4中的has_many:through关系

时间:2013-12-15 19:07:41

标签: ruby-on-rails ruby-on-rails-4 nested-forms has-many-through rails-admin

我正在尝试弄清楚如何使用https://github.com/sferik/rails_admin/wiki/Has-many-%3Athrough-association示例中给出的位置排序,但不使用受保护的属性,而是使用Rails 4的强参数。如果我尝试使用没有block_ids=的网页上提供的attr_accessible :block_ids功能,则会收到ActiveRecord::UnknownAttributeError错误消息unknown attribute :block_ids。显然,如果我使用attr_accessible :block_ids,它会要求我将protected_attributes添加到我的Gemfile中,这不是Rails 4方式。

是否有人能够使用强参数在rails_admin中为Rails 4设置可订购位置?

1 个答案:

答案 0 :(得分:3)

省略attr_accessible :block_ids并在底部应用替代解决方案对我有效。

PS:Rails 4.2.0,rails_admin为0.6.6

class Grid < ActiveRecord::Base
  has_many :block_grid_associations, :dependent => :delete_all, :autosave => true, :include => :block
  has_many :blocks, :through => :block_grid_associations

  def block_ids=(ids)
    unless (ids = ids.map(&:to_i).select { |i| i>0 }) == (current_ids = block_grid_associations.map(&:block_id))
      (current_ids - ids).each { |id| block_grid_associations.select{|b|b.block_id == id}.first.mark_for_destruction }
      ids.each_with_index do |id, index|
        if current_ids.include? (id)
          block_grid_associations.select { |b| b.block_id == id }.first.position = (index+1)
        else
          block_grid_associations.build({:block_id => id, :position => (index+1)})
        end
      end
    end
  end

  rails_admin do
    configure :block_grid_associations do
      visible(false)
    end

    configure :blocks do
      orderable(true) # only for multiselect widget currently. Will add the possibility to order blocks
      # configuration here
    end
  end
end