Вот код, делающий то, что вы хотите, я упростил ваши модели, но он должен ответить на ваш вопрос.
Пример может работать сам по себе без 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;