2016-11-22 60 views
0

我使用的是Activeadmin,並有一個表單,用戶可以選擇他們想要添加notenotebook基於事先選擇的Rails集合

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

但是,我希望能夠根據用戶選擇的筆記本動態更改該集合。如果筆記本的notebook_typeevernote,我不想讓用戶選擇Note.all中包含的某些筆記。 (我已經在一個非常親切的StackOverflow用戶的幫助下得到了這個範圍)。

僅供參考,下面的方法:

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:,具體取決於用戶選擇了哪個Notebook。

非常感謝您的任何幫助。

回答

0

恕我直言,最好的解決辦法是創建一個新的member_action,它接收一個筆記本ID並返回所有可用筆記的JSON。

例子:

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

現在,使用jQuery,使筆記本的時候ID更改,清除舊選擇框的所有選項,並添加新的選項請求。

例子:

$("#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>'); 
     }); 
    }); 
}); 

這是一個想法......用它作爲基地,爲您的解決方案。