Помощь с HABTM: через - PullRequest
       1

Помощь с HABTM: через

3 голосов
/ 28 декабря 2010

Моя текущая реализация HABTM до сих пор работает с: has_and_belongs_to_many.Уведомление и конфиденциальность наследуются от предпочтения.Предпочтение - это ИППП.Я хочу попробовать использовать: has_many,: через ассоциацию.

Файлы моделей

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

Файлы миграции

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

Я попробовал следующее

class User < ActiveRecord::Base
  has_many :preferences, :through => :preferences_users
end

class Preference < ActiveRecord::Base
  has_many :users, :through => :preferences_users
end

Моя форма выглядит как

  <% 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 %>

Я получаю

Could not find the association :preferences_users in model User

Что я делаю не так?Проблема в моей форме или в моей ассоциации?

Ответы [ 2 ]

6 голосов
/ 28 декабря 2010

Хорошо, получил его на работу. Мне нужна была модель PreferencesUser, и отсутствовал has_many: preferences_users в моделях пользователя и предпочтений:

class PreferencesUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :preference
end

class User < ActiveRecord::Base
  has_many :preferences_users
  has_many :preferences, :through => :preferences_users
end

class Preference < ActiveRecord::Base
  has_many :preferences_users
  has_many :users, :through => :preferences_users
end

Не нужно было ничего менять в моей форме. Надеюсь, это кому-нибудь поможет

1 голос
/ 28 декабря 2010

Ассоциация HABTM создана для создания отношения N к N, что вы хорошо сделали, но не очень пригодились.Ассоциация has_many создана для создания отношения 1-N и является хорошим выбором.

Вам необходимо:

  • добавить has_many: предпочтения в вашей модели пользователя (так же, каквы сделали)
  • добавьте принадлежность__: пользователя в вашей модели предпочтений
  • добавление user_id в таблицы предпочтений

Обычно мы используем: through для связывания объектов, которые ненапрямую связаны, например, Пользователи соединились со статьями, потому что они опубликовали комментарий к некоторым статьям.

Другое полезное использование - это условные отношения NN, например, класс дружбы:

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
end 

ДляПридерживаясь своих потребностей, вы можете сделать следующее:

#in you User model
has_many :notifications, :source => :preferences
has_many :privacies, :source => :preferences

#in your Preference model
belongs_to :user
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...