Dimitri de Ruiter Dimitri de Ruiter - 1 month ago 4x
Ruby Question

Rails: get an index of selected records

To learn rails and ruby, I building my first app. I trying to find out how to get a list of records (like index) that matches selection criteria. I want to use this in a view to check a condition on an event (click the save button). In my controller, for example I have:

def index
@annotations = Annotation.all.order(:created_at)

Now this lists all - how do I restrict it to those annotations where field 1 matches field 1 of the record I save && field 2 matches field 2 the record ? If the count of selected records is greater then 0, then save should not take place. Looks like a callback before_save.

May be said differently: I want to count the number of annotations that where the values of fields 1 and field 2 match.


Apply uniqueness validation using validates_uniqueness_of

class Annotation < ActiveRecord::Base
  validates_uniqueness_of :field_1, scope: [:field_2, :field_3]

This will not let you save the duplicate record