perpetuum mobile
12. 09. 2014. ruby

ActiveRecord notes

Contents


Uniqueness on a combination of fields

In the model:

validates :name, presence: true, uniqueness: { scope: :genus, message: Species::NAME_GENUS_VALIDATION_ERROR }
validates :genus, presence: true

In the spec:

subject { FactoryGirl.create(:species) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:genus).with_message(Species::NAME_GENUS_VALIDATION_ERROR) }

Before testing uniqueness a record must be created.
In the migration:

add_index :species, [:name, :genus]

The index should be added on to the fields to enforce field combination uniqueness in the database.

Resources


Inclusion in array

In the model: validates :role, presence: true, inclusion: {in: ROLES}

In the spec:

it { is_expected.to ensure_inclusion_of(:role).in_array(User::ROLES) }

Getting all model associations

model_class(model).reflect_on_all_associations.map { |a| a.name }

Overriding model getters and setters

def habitats
  read_attribute(:habitats)
end

def habitats=(value)
  write_attribute(:habitats, value)
end

Serialization

In model:

serialize :substrates, JSON

In controller:

def permitted_params
  @params ||= params.require(:characteristics).permit(PUBLIC_FIELDS).tap do |white_listed|
    white_listed[:substrates] = params[:characteristics][:substrates]
  end
end

When searching:

Characteristic.where(substrates: ["flash", "branches", "leaves"].to_json)

resources