My current HABTM implementation still works: has_and_belongs_to_many. Notification and privacy are both inherited from Preferences. Preference is STI. I want to try using: has_many ,: through an association.
Model Files
class User < ActiveRecord::Base
has_and_belongs_to_many :preferences
end
class Preference < ActiveRecord::Base
has_and_belongs_to_many :users
end
class Notification < Preference
end
class Privacy < Preference
end
Migration files
class UsersHaveAndBelongToManyPreferences < ActiveRecord::Migration
def self.up
create_table :preferences_users, :id => false do |t|
t.references :preference, :user
t.timestamps
end
end
def self.down
drop_table :preferences_users
end
end
class CreatePreferences < ActiveRecord::Migration
def self.up
create_table :preferences do |t|
t.string :title
t.text :description
t.string :type
t.timestamps
end
end
def self.down
drop_table :preferences
end
end
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
I tried the following
class User < ActiveRecord::Base
has_many :preferences, :through => :preferences_users
end
class Preference < ActiveRecord::Base
has_many :users, :through => :preferences_users
end
My form looks like
<% Preference.where(:type => 'Notification').all.each do |notification| %>
<li>
<%= check_box_tag 'user[preference_ids][]', notification.id, @user.preference_ids.blank? ? false : @user.preferences.include?(notification) %>
<%= label_tag notification.description %>
</li>
<% end %>
I get
Could not find the association :preferences_users in model User
What am I doing wrong? Is the problem in my form or in my association?
source
share