在Active Record中获取每个属性的唯一记录

时间:2015-06-10 08:10:57

标签: ruby-on-rails activerecord

我有学生模型,我希望每个term_id获得一条记录(其中一个属性)。

Student.select(:term_id).distinct 

有效,但结果是一个term_ids数组,而不是对象本身 - 这是我想要的

2 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function(){

  loadGallery(true, 'a.thumbnail');

  //This function disables buttons when needed
  function disableButtons(counter_max, counter_current){
    $('#show-previous-image, #show-next-image').show();
    if(counter_max == counter_current){
      $('#show-next-image').hide();
    } else if (counter_current == 1){
      $('#show-previous-image').hide();
    }
  }
  function loadGallery(setIDs, setClickAttr){
    var current_image,
        selector,
        counter = 0;

    $('#show-next-image, #show-previous-image').click(function(){
      if($(this).attr('id') == 'show-previous-image'){
        current_image--;
      } else {
        current_image++;
      }

      selector = $('[data-image-id="' + current_image + '"]');
      updateGallery(selector);
    });

    function updateGallery(selector) {
      var $sel = selector;
      current_image = $sel.data('image-id');
      $('#image-gallery-caption').text($sel.data('caption'));
      $('#image-gallery-title').text($sel.data('title'));
      $('#image-gallery-image').attr('src', $sel.data('image'));
      disableButtons(counter, $sel.data('image-id'));
    }

    if(setIDs == true){
      $('[data-image-id]').each(function(){
        counter++;
        $(this).attr('data-image-id',counter);
      });
    }
    $(setClickAttr).on('click',function(){
      updateGallery($(this));
    });
  }
});

答案 1 :(得分:0)

Student.select("DISTINCT term_id, `students`.* ")

如果您使用旧版本的ruby(< 2.3.8),

,请注意
Student.find(:all, :select => "DISTINCT(term_id), `students`.*")

或者如果您想单独id

Student.find(:all, :select => "DISTINCT(term_id), id")

学生是你的桌名。您将获得一系列对象。