Skip to content

Instantly share code, notes, and snippets.

@kjellski
Last active December 17, 2015 16:29
Show Gist options
  • Save kjellski/5638704 to your computer and use it in GitHub Desktop.
Save kjellski/5638704 to your computer and use it in GitHub Desktop.
has_and_belongs_to_many confusion
class Poi < ActiveRecord::Base
attr_accessible :activities
has_and_belongs_to_many :activities
end
class Activity < ActiveRecord::Base
attr_accessible :pois
has_and_belongs_to_many :pois
end
# none of these are working, all because of errors along these lines:
#
# Failure/Error: @poi1.activities.create({:activity_id => @activity1.id })
# ActiveModel::MassAssignmentSecurity::Error:
# Can't mass-assign protected attributes: activity_id
@poi1.activities.create({:activity_id => @activity1.id })
@poi1.activities.create({:activity => @activity1 })
@poi1.activities.create(activity: @activity1)
@poi1.activities << @activity1
class AddActivitiesPoisJoinTable < ActiveRecord::Migration
def change
create_table :activities_pois do |t|
t.integer :activity_id
t.integer :poi_id
t.timestamps
end
add_index :activities_pois, [:activity_id, :poi_id]
add_index :activities_pois, [:poi_id, :activity_id]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment