Skip to content

Instantly share code, notes, and snippets.

@chrismo
Last active January 25, 2016 15:53
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 chrismo/1212a7cbc6e2bff09669 to your computer and use it in GitHub Desktop.
Save chrismo/1212a7cbc6e2bff09669 to your computer and use it in GitHub Desktop.
Answer to creating multiple has_many records
require 'active_support'
require 'active_record'
require 'minitest/autorun'
ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => ':memory:'
class Skill < ActiveRecord::Base
connection.create_table table_name, :force => true do |t|
t.string :name
end
end
class Job < ActiveRecord::Base
has_many :abilities
has_many :skills, through: :abilities
connection.create_table table_name, :force => true do |t|
t.string :name
end
end
class Ability < ActiveRecord::Base
belongs_to :job
belongs_to :skill
connection.create_table table_name, :force => true do |t|
t.integer :job_id
t.string :skill_id
end
end
describe 'stuff' do
before do
Skill.create!(name: 'selling')
Skill.create!(name: 'buying')
Skill.create!(name: 'processing')
Skill.create!(name: 'repairing')
Skill.create!(name: 'kick-boxing')
end
it 'creates multiple abilities' do
params = {
'job' => {
'name' => 'abc',
'skill_ids' => ['2', '5']
},
}.with_indifferent_access
job = Job.create(params[:job])
assert_equal ['buying', 'kick-boxing'], job.skills.map(&:name)
end
end
source 'https://rubygems.org'
gem 'activerecord', '~> 4.2'
gem 'sqlite3'
GEM
remote: https://rubygems.org/
specs:
activemodel (4.2.5)
activesupport (= 4.2.5)
builder (~> 3.1)
activerecord (4.2.5)
activemodel (= 4.2.5)
activesupport (= 4.2.5)
arel (~> 6.0)
activesupport (4.2.5)
i18n (~> 0.7)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
arel (6.0.3)
builder (3.2.2)
i18n (0.7.0)
json (1.8.3)
minitest (5.8.4)
sqlite3 (1.3.11)
thread_safe (0.3.5)
tzinfo (1.2.2)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord (~> 4.2)
sqlite3
BUNDLED WITH
1.10.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment