text
stringlengths
10
2.61M
class CreateParts < ActiveRecord::Migration def change create_table :parts do |t| t.belongs_to :movie, index: true t.belongs_to :actor, index: true t.timestamps null: false end end end
require "test_helper" describe SessionsController do describe "auth_callback" do it "logs in an existing user and redirects to the root route" do # Count the users, to make sure we're not (for example) creating # a new user every time we get a login request start_count = User.count login...
class User < ApplicationRecord has_many :entries, :through => :streams end
class AddPdbfileToPdb < ActiveRecord::Migration def change add_column :pdbs, :pdbfile, :string end end
class DeviseAuthy::PasswordsController < Devise::PasswordsController ## # In the passwords controller a user can update their password using a # recovery token. If `Devise.sign_in_after_reset_password` is `true` then the # user is signed in immediately with the # `Devise::Controllers::SignInOut#sign_in` metho...
# frozen_string_literal: true require 'test_helper' describe Page do before do @page = Page.new @page.url = 'http://example.com/' # mock the request stub_request(:any, 'http://example.com/'). to_return(status: 200, headers: {}, body: <<EOF <!doctype html> <html> <head> <title>Exampl...
RSpec.shared_examples "a paginable resource" do |options| context "when page #{options[:page]} limit #{options[:limit]}" do let!(:req) do get "/bucketlists", { page: options[:page], limit: options[:limit] }, headers end let!(:size) { correct_size(options) } let(:bucketlist_id) { correc...
class Custom include DataMapper::Resource # property <name>, <type> property :id, Serial property :name, String property :phone, String property :email, String property :status, String property :memo, Text property :created_at, DateTime property :updated_at, DateTime end
# ask the user for two numbers # ask the user for the operation to perform # perform the operation on the two numbers # display the result require 'yaml' MESSAGES = YAML.load_file('calculator_messages.yml') LANGUAGE = 'es' def messages(message,lang='en') MESSAGES[lang][message] end def prompt(key) message = mes...
module RiakRest # Client for restful interaction with a Riak document store via the Jiak # HTTP/JSON interface. RiakRest Core Client classes expose Jiak server # constructs and concepts. JiakResource wraps Jiak interaction at a higher # level of abstraction and takes care of much of the Core Client bookkeeping...
require_relative 'collision' class SeaObject attr_accessor :area_size, :vertices, :x0, :y0, :neighbours, :collision_array def initialize area_size, x0, y0 @area_size = area_size @x0 = x0 @y0 = y0 @neighbours = [] @vertices = [] @collision_array = [] @ce...
class V1::Dashboards::Manager::UsersController < V1::BaseController include V1::MessageHelper def list authorize! :list, User data = load_user params[:kind] render status: 200, json: data end def approve u = User.find(params[:id]) authorize! :manage, u sta = "error" if u.is_teacher_...
class RenameCreatorOnIssue < ActiveRecord::Migration def change rename_column :issues, :created_by_id, :creator_id end end
require 'rails_helper' feature "static pages" do let!(:tatooine) { FactoryGirl.create(:planet) } scenario "user visits root path" do visit root_path expect(page).to have_content "Far, Far Away Travel" expect(page).to_not have_content tatooine.name end scenario "user visits about page" do vis...
class CreateAccounts < ActiveRecord::Migration def up execute %{ CREATE DOMAIN currency numeric NOT NULL DEFAULT 0; CREATE DOMAIN positive_currency numeric NOT NULL DEFAULT 0 CONSTRAINT non_negative CHECK (VALUE > 0); CREATE DOMAIN non_negative_currency numeric NOT NULL DEFAULT...
Rails.application.routes.draw do mount RailsAdmin::Engine => '/admin_console', as: 'rails_admin' devise_for :admins devise_for :users, controllers: {registrations: "registrations"} root to: "welcome#index" resources :subscribers resources :products end
class CreateGroupEvents < ActiveRecord::Migration[5.1] def change create_table :group_events do |t| t.string :name t.string :description t.string :location t.datetime :starts_at t.datetime :ends_at t.boolean :published, default: false t.timestamps end e...
FactoryBot.define do factory :producer, class: "Producer" do full_name { "山田 太郎" } postal_code { "123-4567" } address { "東京都新宿区1-1-1" } corporate_name { "山田漁業" } tel { "012-3456-7890" } email { "test@email.com" } password { "password" } password_confirmation { "password" } birthday...
# frozen_string_literal: true module LightSerializer VERSION = '0.0.1' end
require_relative 'global.rb' require_relative 'release.rb' module Shasum FILE = "#{Global::BASE_DIR}/etc/shasums.txt" def self.read(qfn, release, platform_name) sums = read_file key = key(qfn, release, platform_name) sums[key] end def self.update(qfn, release, platform_name, shasum) sums = r...
class Access < ActiveRecord::Base belongs_to :user belongs_to :project validates :user_id, :presence => true validates :project_id, :presence => true end
Hanami::Model.migration do change do create_table :goals do primary_key :id column :title, String, null: false column :description, String, null: false, default: '' column :completed_at, DateTime, null: true column :created_at, DateTime, null: false column :upd...
class Client < ApplicationRecord has_many :projects, dependent: :restrict_with_error has_many :hours, through: :projects belongs_to :user belongs_to :default_rate, class_name: "Rate" validates_presence_of :user, :name, :default_rate def to_s name end end
class LessonsController < ApplicationController before_action :authenticate_user! before_action :require_enrolled_for_current_course, :only => [:show] def show end private helper_method :current_lesson def current_lesson @current_lesson ||= Lesson.find(params[:id]) end def require_enrolled_for_curre...
class ReviewsController < ApplicationController include SpotifyMethod def index end def new @review_form = ReviewForm.new unless user_signed_in? flash[:alert] = 'ログインが必要です' redirect_to new_user_session_path end end def create @review_form = ReviewForm.new(review_params) pa...
require 'csv' require File.expand_path(File.join(File.dirname(__FILE__), "db")) require File.expand_path(File.join(File.dirname(__FILE__), "tweet")) require File.expand_path(File.join(File.dirname(__FILE__), "test_data")) class Populator def populate(file) Tweet.delete_all TestData.delete_all ...
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../dummy/config/environment', __FILE__) require 'rspec/rails' require_relative '../lib/anonymized' RSpec.configure do |config| abort("The Rails environment is running in production mode!") if Rails.env.production? ActiveRecord::Migration.maintain_test_schema! ...
#! /usr/bin/ruby # # GenomeAnnotation.rb # ver 1.0.3 # This class is used for searching in annotation table quickly # # Copyright (c) 2016 - Ryo Kanno # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # require 'csv' class GenomeAnnotation attr_reader :header at...
class Device include MongoMapper::Document belongs_to :user, :class_name => "User" key :device_token, String, :required => true, :unique => true one :token, :foreign_key => :token_id, :class_name => "Token" key :device_name, String key :model, String key :system_version, String key :app_version, Strin...
require 'test_helper' class ConstituentsControllerTest < ActionController::TestCase setup do @constituent = constituents(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:constituents) end test "should get new" do get :new assert_respon...
class CreateEmployees < ActiveRecord::Migration[5.0] def change create_table :employees, id: :uuid do |t| t.uuid :company_id, null: false t.string :first_name t.string :last_name t.jsonb :details, null: false, default: {} t.time :deleted_at t.timestamps end add_index :e...
# frozen_string_literal: true module Blacklight module Response # Render spellcheck results for a search query class ViewTypeComponent < ViewComponent::Base # @param [Blacklight::Response] response def initialize(response:, views: {}, search_state:, selected: nil) @response = response ...
#!/usr/bin/env ruby require 'thor' require 'net/ssh' require 'net/http' class Bootstrap < Thor desc 'bootstrap droneIp dronePassword ', 'Bootstraps a drone using SSH' def bootstrap(drone_ip, password) master_ip = Net::HTTP.get(URI.parse('http://ipecho.net/plain')) p "Found master ip to be: #{master_ip}" ...
module Ml class TokenCompressor DEFAULT_STOP_WORD_FILE = "#{File.dirname(__FILE__)}/../../config/stop-words_english_3_en.txt" def initialize(options={}) @stem_words = options[:stem_words] || [] @stop_words = options[:stop_words] || default_stop_words end # FIXME: use lazy enumerators inst...
class User < ActiveRecord::Base has_many :games has_many :decks, :through=> :games validates :username, :uniqueness => true, :presence => true end
class ItemsController < ApplicationController def index @person = Person.find_by_user_id(current_user.id) @show_your_items = params[:your_items] @interactions = nil if @show_your_items == 'true' @user_items = @person.items else @user_items = Item.where(...
class FixDeleteTriggerOnTransactions < ActiveRecord::Migration def up execute %{ DROP TRIGGER update_balances ON transactions; DROP FUNCTION update_balances(); CREATE FUNCTION insert_transaction_update_balances() RETURNS trigger AS $BODY$ BEGIN PERFORM update_a...
class User < ActiveRecord::Base has_many :combinis has_many :likes has_many :comments has_many :products, through: :inventory_items has_many :inventory_items belongs_to :title has_many :achievements, through: :achievement_users has_many :achievement_users end
class AddOperatingRoomsToTrip < ActiveRecord::Migration def self.up add_column :trips, :available_rooms, :integer add_column :case_groups, :room_number, :integer add_index :case_groups, :room_number end def self.down remove_index :case_groups, :room_number remove_column :case_groups, :room_nu...
module ApplicationHelper def format_money(cents) number_to_currency((cents || 0) / 100.0) end def button_class_for_item(list, item) item.lowest_price?(list) ? 'lowest' : 'not-lowest' end def row_class_for_item(item) current_user.items.include?(item) ? 'added' : 'not-added' end def flash_m...
class User < ApplicationRecord # ecrypt password has_secure_password # validations validates_presence_of :first_name, :email, :password_digest validates_uniqueness_of :email, case_sensative: false validates_format_of :email, with: /@/ before_save :email_to_downcase def email_to_downcase self.email = self...
class FontFiraSansExtraCondensed < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/firasansextracondensed" desc "Fira Sans Extra Condensed" homepage "https://fonts.google.com/specimen/Fira+Sans+Extra+Condensed" def install (share/"font...
class JadDownloadStrategy < CurlDownloadStrategy def stage # the JAD tarball contains odd parent directory references, which unzip does not handle by default # -j -d forces all files to be extracted in the directory "JAD" safe_system "/usr/bin/unzip", "-j", "-d", "JAD", cached_location chdir end end...
require "spec_helper" describe Emailer do before :each do @user = FactoryGirl.create(:user) end describe "welcome email" do let(:mail) { Emailer.welcome_email(@user) } it "renders the headers" do mail.subject.should eq("Welcome to basapp!") mail.to.should eq([@user.email]) mail.fr...
class GamesController < ApplicationController def index @banners = Banner.all.limit(3) @recomended = Game.where(recommended: true).limit(8) @most_visited = Game.all.order("visit") end def create @game = Game.new resource_params if @game.save redirect_to root_path else redirec...
require 'pry' WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [3, 5, 7]] INITIAL_MARKER = ' ' PLAYER_MARKER = 'X' COMPUTER_MARKER = 'O' WINS_FOR_MATCH = 5 WAITING_TIME = 3 first = '' current = '' def prompt(msg) puts "=> #{msg}" e...
require_relative '../spec_helper' describe "When a user visits show" do it "they see one day of weather" do weather = Condition.create(date: "01/05/2017", max_temperature_f: "90", mean_temperature_f: "75", min_temperature_f: "19", ...
class Listing < ActiveRecord::Base belongs_to :county belongs_to :parish before_save :titleize_city before_create :titleize_city def titleize_city self.town = self.town.titleize end end
class Message attr_reader :name, :message, :room_id def initialize(attributes) @name = attributes[:name] @message = attributes[:message] @room_id = attributes[:room_id] end def self.create(attributes) post_message = Faraday.post do |request| request.url 'http://localhost:3000/messa...
require 'bundler/setup' require 'sinatra' require 'slim' require 'bigdecimal/math' class Debug < BasicObject def initialize(obj) @obj = obj end def method_missing(*args, &b) ::Kernel.puts args.inspect @obj.send(*args, &b) end end helpers do def render(engine, template, options = {}, locals = {}...
# == Schema Information # # Table name: videos # # id :integer not null, primary key # title :string # caption :string # url :string # short_url :string # league_id :integer # created_at :datetime not null # updated_at :datetime not null # module VideosHelper ...
require 'spec_helper' describe "Posts" do before do @post = Post.create :title => 'New post', :content => 'Some text for the post.' end describe "GET /posts" do it "displays some posts" do visit posts_path page.should have_content "New post" end it "creates a new post" do visit ...
require_relative '../shapes/cube' class SelectionCube def initialize(gam_main_instance) @active = true @gam_main_instance = gam_main_instance end def active? @active end def finish @active = false difference_vector = @second_point.sub(@first_point) ...
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'walrat' module Walrat # Predicates parse input without consuming it. # On success they throw a subclass-specific symbol (see the AndPredicate and # NotPredicate classes). # On failure they...
require 'chemistry/dsl' Chemistry::DSL.element "Uut" do symbol "Uut" atomic_number 113 atomic_weight 284 melting_point end
class ChangeUsersAuthenticationTokenTimeToDatetime < ActiveRecord::Migration def change remove_column :users, :authentication_token_time add_column :users, :authentication_token_time, :datetime end end
module Campaigns module CreateCsvExport class Service private attr_reader :campaigns, :csv_export, :filename, :builder_class public def initialize(campaigns, builder_class: Builder) @campaigns = campaigns @builder_class = builder_class end def call ...
module MonthlyReports class BuildCategoriesBreakdownEvolutionDataService def initialize(monthly_reports) @monthly_reports = monthly_reports end def call @categories = Category.all categories_data end private def categories_data @categories.map do |category| ...
# Based on the information given above, write a method that takes an array as an argument. # In that method, yield the contents of the array to a block. In the block, write your block # variables in such a way that the first two items are discarded, and the last two items are treated as birds of prey. def types(arra...
# frozen_string_literal: true class ManagerValidator ERROR_MESSAGES = { has_manager: "Error: Collaborator already has a manager", not_in_company: "Error: Couldn't apply because the collaborator is not in the same company", hierarchy_below: "Error: Couldn't apply because the collaborator is in a hierarchy...
module AccountingEntries class Create def initialize(args:) @args = args @date_prepared = @args[:date_prepared] @book = @args[:book] @particular = @args[:particular] end def run @accounting_entry = AccountingEntry.new( dat...
Given(/^I am on the homepage$/) do visit '/' end When(/^I follow "(.*?)"$/) do |link_name| click_link(link_name) end Then(/^I should see "(.*?)"$/) do |text| expect(page).to have_content(text) end Then(/^I should not see "(.*?)"$/) do |text| expect(page).not_to have_content(text) end When (/^I fill "(.*?)" w...
require 'rails_helper'; describe 'User registration' do let(:email) { 'registration_test_user@example.org' } let(:password) { 'password' } let(:first_name){'john'} let(:last_name){'Doe'} let(:phone_no){'9172083523'} before :each do @user = FactoryGirl.create(:admin_user) login_as(@user) visit...
class AddIndexOnFeeAccountIdToFinanceFeeCollection < ActiveRecord::Migration def self.up add_index :finance_fee_collections, :fee_account_id, :name => "index_by_fee_account_id" end def self.down remove_index :finance_fee_collections, :fee_account_id, :name => "index_by_fee_account_id" end end
require 'rails_helper' describe ApplicationHelper do let(:link_path) { "/profile/edit" } it 'true if current page' do allow(self).to receive(:current_page?).with(link_path).and_return(true) expect(is_active?(link_path)).to eq("active") end end
ActiveAdmin.register Event do menu false controller do def scoped_collection super.includes :characters, :character_events end end member_action :award_attendance do characters = CharacterEvent.where(event: resource) characters.map(&:give_attendance_awards) redirect_to resource_path,...
module SeasonStatistics def games_from_season(season_id) game_teams.find_all do |game_team| game_team.game_id.to_s[0...4] == season_id[0...4] end end def get_team_name(team_id) teams.find {|team| team.team_id.to_i == team_id}.teamname end def group_by_coach(season_id) games_from_seaso...
class BookItem attr_reader :status def initialize title, authors, language, barcode, status, rack_id, lending_id @title = title @authors = authors @language = language @barcode = barcode @status = status @lending_id = lending_id @rack_id = rack_id end...
@random_player = %w[Player Computer] @winning_score = 5 @player_score = 0 @computer_score = 0 WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [3, 5, 7]].freeze INITIAL_MARKER = ' '.freeze PLAYER_MARKER = 'X'.freeze COMPUTER_MARKER = 'O...
class TransportFeeFinanceTransaction < ActiveRecord::Base belongs_to :transport_fee belongs_to :finance_transaction belongs_to :parent, :class_name => 'TransportFeeFinanceTransaction' belongs_to :child, :foreign_key => :id, :primary_key => :parent_id, :class_name => 'TransportFeeFinanceTransaction', :condition...
class ContentsController < ApplicationController before_action :authenticate_user!, except: [:index] before_action :move_to_index, only: [:edit, :update, :destroy, :study] def index @contents = Content.all if user_signed_in? @my_contents = Content.where(user_id: current_user.id) end if @con...
require 'test_helper' class HomeControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end test "should load the home page even when not logged in" do get home_path assert_response :success end test "should get the home page when logged in" do @user = User.cre...
class RevertToBellTableNames < ActiveRecord::Migration def self.up rename_table :audiences, :titleaudience rename_table :boilers, :documentnames rename_table :docs, :document rename_table :domained_docs, :documentdomain rename_table :domains, :domainlist rename_table :expirations, :expire ...
require 'fog/radosgw/core' require 'fog/json' require 'fog/xml' module Fog module Radosgw class Provisioning < Fog::Service class UserAlreadyExists < Fog::Radosgw::Provisioning::Error; end class NoSuchUser < Fog::Radosgw::Provisioning::Error; end class ServiceUnavailable < Fog::Radosgw::Prov...
class AddFilesizeToCommandFile < ActiveRecord::Migration[5.2] def change add_column :command_files, :filesize, :integer end end
desc 'Runs cron maintenance tasks.' task cron: :environment do puts "Running cron at #{Time.now.strftime('%Y/%m/%d %H:%M:%S')}..." Shelf.all.each(&:annotate_books!) puts "Done running cron at #{Time.now.strftime('%Y/%m/%d %H:%M:%S')}..." end
# typed: true class CreateHartScienceExperiments < ActiveRecord::Migration[6.0] def change create_table :hart_science_experiments do |t| t.text :text t.string :url t.timestamps end end end
# frozen_string_literal: true require 'faraday' require 'json' require 'tmpdir' require 'openssl' require 'retriable' require 'logger' # Do not fail if SSL negotiation with DSpace isn't working OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE module Orangetheses class Fetcher attr_writer :logger # @p...
require "spec_helper" describe Concern::Associations::AssetAssociation do #-------------------- describe '#asset_json' do it "uses simple_json for the asset" do record = create :test_class_story asset = create :asset, caption: "Hello", asset_id: 999, position: 4 record.assets << asset ...
# # fmw_jdk_linux_rpm # # Copyright 2015 Oracle. All Rights Reserved # Puppet::Type.type(:fmw_jdk_linux_rpm).provide(:fmw_jdk_linux_rpm) do def install name = resource[:name] source_file = resource[:source_file] Puppet.info "instal Java RPM for #{name}" rpm_status = Puppet::Util::Executio...
class ApplicationController < ActionController::Base protect_from_forgery # rescue_from Cancan::AccessDenied do |exception| # redirect_to root_url, :alert => exeption.message # end def after_sign_in_path_for(resource) welcome_index_path end end
class Dog def name=(full_name) @name = full_name end def name "#{@name}" end def breed=(type) @breed = type end def breed "#{@breed}" end end
# SwitchInterpreter is the main class used to interact with the Whatnot library. # # == Role # # Minisat understands a constraint in terms like this: # # 100 101 102 103 0 # -100 -101 0 # -100 -102 0 # -100 -103 0 # -101 -102 0 # -101 -103 0 # -102 -103 0 # # Humans understand a constraint more like this:...
# frozen_string_literal: true module ImportUsers # Course completion import for user importing class CourseCompletions def initialize(user, row) @user = user @row = row @completions = [] end def call completions_data.each { |(key, date)| process_completions(key, date) } ...
=begin #============================================================================== ** Skill Type Groups Author: Hime Date: Aug 29, 2013 ------------------------------------------------------------------------------ ** Change log Aug 29, 2013 - updated script, changed name Jun 13, 2012 - added multiple s...
class TripsController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource :only => [:index] def new @trip = Trip.new end def index end def edit @trip = Trip.find(params[:id]) authorize! :update, @trip end def update @trip = Trip.find(params[:id])...
class ApiType < ActiveRecord::Base has_many :clients has_many :visits attr_accessible :name end
feature "Portal - Create" do context 'Visitor' do scenario "Access invalid" do visit new_portal_path expect(current_path).to eq new_session_path end end context 'Admin' do let(:user) { create :user} background do login user.email, user.p...
dictionary = { :hello => 'hi', :to => '2', :two => '2', :too => '2', :for => '4', :four => '4', :be => 'b', :you => 'u', :at => '@', :and => '&' } def word_substituter(tweet) dictionary = { :hello => 'hi', :to => '2', :two => '2', :too => '2', :for => '4', :four => '4', ...
module Sinatra module ContentFor2 def self.included(base) #:nodoc: base.send(:include, CurrentTemplateEngine) unless base.method_defined?(:current_template_engine) end module CurrentTemplateEngine attr_reader :current_template_engine def render(engine, *) #:nodoc: @current_temp...
require 'tilt' module Ehaml def self.compile(name, string) result = [] result.push 'window.T || (window.T = {});' result.push "T['#{name}'] = " result.push string.split("\n").map {|l| "\"#{l.gsub('"', '\"').strip}\""}.join('+') result.push ';' result.join end end module Sprockets class E...
class ProductsController < ApplicationController before_action :set_product def index @products = Product.all end def show @product.increment!(:score) end def add_to_cart current_cart.add(@product) unless current_cart.items.include?(@product) redirect_to :back end private def set...
class CreateGames < ActiveRecord::Migration[6.0] def change create_table :games do |t| t.string :guest1, null: false t.string :guest2, null: false t.string :guest3, null: false t.integer :rank_bonus_id, null: false t.integer :top_bonus_id, null: false t.integer :rate_id, null: ...
class Parser def initialize(sentence) @sentence = sentence end def video_urls parsed_data['animated'].map do |gif| gif['mp4']['original']['secureUrl'] end end def preview_urls parsed_data['animated'].map do |gif| gif['thumbnail']['original']['secureUrl'] end end private ...
class Score < ApplicationRecord belongs_to :heat belongs_to :judge, class_name: User belongs_to :athlete, class_name: User validates_presence_of :wave, :score end
Rails.application.routes.draw do get '/pages', to: "pages#index" end
require 'rails_helper' RSpec.describe Paper, type: :model do describe "validation" do it "paper without title shouldn't be valid" do Paper.new(:venue => "mind 49: 433-460", :year => 1950).should_not be_valid end it "paper without title shouldn't be valid" do Paper.new(:title => "computing machinery and i...
class EmployeesController < ApplicationController def create @employee = Employee.create(create_employee_params) if @employee.valid? render json: @employee end end def destroy # byebug @employee = Employee.find_by(id: params[:id]) @emplo...
module SequelSpec module Matchers module Validation class ValidateIncludesMatcher < ValidateMatcher def description desc = "validate that #{@attribute.inspect} is included in #{@additionnal.inspect}" desc << " with option(s) #{hash_to_nice_string @options}" unless @options.empty?...
class Item < ApplicationRecord belongs_to :user has_one :purchase_user has_one_attached :image extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :condition belongs_to :burden belongs_to :prefecture belongs_to :period belongs_to :category with_options presence:true do validate...