Rails 基于先前选择的集合

Rails collection based on prior selection

我正在使用 Activeadmin 并有一个表单,用户可以在其中选择 notebook 他们想要添加 note 的表单。

f.input :notebook
f.input :note, as: :select, collection: Note.all

但是,我希望能够根据用户选择作为笔记本的内容动态更改该集合。如果笔记本的 notebook_typeevernote,我不想让用户选择 Note.all 中包含的一些笔记。 (在一位非常友善的 Whosebug 用户的帮助下,我已经缩小了范围)。

供参考,方法如下:

class Notebook < ActiveRecord::Base
  has_many :notes

  def self.notes_without_check_lists
    all.reject { |notebook| notebook.notes.any? { |note| note.note_type == 'check_list' } }
  end
end

我已经在使用一些 jQuery 来处理表单的另一部分并使用这样的更改事件:

$("#note_notebook_id").on 'change', (e) ->

但本质上,我想以某种方式根据用户选择的笔记本在 Note.allNote.notes_without_check_lists 之间切换 collection:

非常感谢您的帮助。

恕我直言,最好的解决方案是创建一个新的 member_action 接收一个笔记本 ID 和 return 它的所有可用笔记的 JSON。

示例:

member_action :notes, method: :get do
  notebook = Notebook.find params[:notebook_id]
  render :json, notebook.notes_without_check_lists
end

现在,使用jQuery在notebook id更改时发出请求,清除旧select框的所有选项并添加新选项。

示例:

$("#note_notebook_id").on('change', function() {
    var nb_id = $(this).val();
    $.get('http://yourdomain/admin/notebook/notes?notebook_id=' + nb_id, function(result) {
        $('#note').empty();
        $.each(result.data, function(item) {
           $('#note').append('<option value="'+item.id+'">'+item.name+'</option>');
        });
    });
});

这是一个想法...将其用作解决方案的基础。