Skip to content

Instantly share code, notes, and snippets.

@cristianbica
Created December 7, 2022 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristianbica/489ebafb0e5c69e78984f8e7f083b982 to your computer and use it in GitHub Desktop.
Save cristianbica/489ebafb0e5c69e78984f8e7f083b982 to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'rails'
gem 'sqlite3', platform: 'ruby'
end
require 'active_record'
require 'action_controller/railtie'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'so74593543')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :companies, force: true do |t|
t.string :name
t.timestamps
end
create_table :verticals, force: true do |t|
t.string :name
t.timestamps
end
create_table :company_verticals, force: true do |t|
t.references :company
t.references :vertical
t.timestamps
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Company < ApplicationRecord
has_many :company_verticals, dependent: :destroy
has_many :verticals, through: :company_verticals
end
class Vertical < ApplicationRecord
has_many :company_verticals
has_many :companies, through: :company_verticals
end
class CompanyVertical < ApplicationRecord
belongs_to :company
belongs_to :vertical
validates_uniqueness_of :vertical_id, scope: :company_id
end
class TestApp < Rails::Application
secrets.secret_token = 'secret_token'
secrets.secret_key_base = 'secret_key_base'
config.logger = Logger.new($stdout)
Rails.logger = config.logger
Rails.application.config.host_authorization = { exclude: ->(request) { true } }
routes.draw do
resources :companies
end
end
class CompaniesController < ActionController::Base
include Rails.application.routes.url_helpers
def create
Rails.logger.debug params.inspect
company_params = params.require(:company).permit(:name, vertical_ids: [])
company = Company.create(company_params)
render inline: company.persisted? ? 'success' : 'failure'
end
end
require 'minitest/autorun'
class PrimaryCategoriesTest < Minitest::Test
include Rack::Test::Methods
def test_index
Vertical.create(id: 1, name: 'Vertical 1')
Vertical.create(id: 2, name: 'Vertical 2')
post '/companies', { company: { name: 'Test', vertical_ids: ["", "1", "2"] } }
# if you use instead the below line it will trigger the behaviour you're experiencing
# post '/companies', { company: { name: 'Test', vertical_ids: ["", "1", "2", "2"] } }
assert_equal "success", last_response.body
end
private
def app
Rails.application
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment