Simple Rails Model - подписка пользователей на темы - PullRequest
2 голосов
/ 05 декабря 2011
class Todo < ActiveRecord::Base
  belongs_to  :user
  belongs_to :assignee, :class_name => "User"
  has_many :comments, :dependent => :destroy
  has_many :subscribers, :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :todos
  has_many :assigned_todos, :class_name => 'Todo', :foreign_key => :assignee_id, :dependent => :destroy
  has_many :comments, :through => :todos
  has_many :subscriptions, :through => :todos, :inverse_of => :subscribers
end

Я пытаюсь заставить пользователей подписаться на задачи.

Я надеюсь, что смогу написать @ todo.subscribeers и получить список пользователей обратно.

Вопросы:

  • Правильны ли мои классовые отношения?
  • Какая структура базы данных мне нужна для подписчиков, если таковая имеется?
  • Если есть лучший подход, пожалуйста, дайте мне знать.

1 Ответ

0 голосов
/ 05 декабря 2011

Вот код, делающий то, что вы хотите, я упростил ваши модели, но он должен ответить на ваш вопрос.

Пример может работать сам по себе без rails, чтобы использовать его с rails, просто игнорируйте заголовки файлов

gem 'activerecord', '~> 3.0.0'

require 'active_record'
require 'mysql2'


ActiveRecord::Base.establish_connection(
    :adapter => 'mysql2',
    :database => 'todos'
  )


# Rails code starts here
class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :todo

end

class Todo < ActiveRecord::Base
  belongs_to  :user
  has_many :subscriptions
  has_many :subscribers, :class_name => "User", :through => :subscriptions

end

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :todos, :through => :subscriptions

end



# create a user and some todos
u = User.find_or_create_by_name("Bob")
u.todos << Todo.create(:text => "do something")
u.todos << Todo.create(:text => "do something else")

# display the todos for this user
p u.todos

А связанная схема MySQL:

# Dump of table subscriptions
# ------------------------------------------------------------

CREATE TABLE `subscriptions` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `todo_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



# Dump of table todos
# ------------------------------------------------------------

CREATE TABLE `todos` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `text` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



# Dump of table users
# ------------------------------------------------------------

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...