2011-12-05 107 views
2
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 

我想让用户订阅todos。简单的导轨模型 - 订阅用户线程

我希望我可以做@ todo.subscribers,并得到用户的列表回来。

问题:

  • 是我的阶级关系是否正确?
  • 什么数据库结构,我需要为用户,如果有的话?
  • 如果有更好的方法,请让我知道。
+0

你试图通过运行这个控制台,看看它是否按照你想要的方式行事? –

+0

是的,我还没有为订户添加表,因为我不确定该模式应该是什么。 – cjm2671

+0

他们订阅了什么?待办事项?你应该把它看作是模型叫做TodosUsers。 –

回答

0

这里是一个代码做你想要什么,我简化你的模型,但它应该回答你的问题。

的例子可以通过自身运行wthout导轨,与导轨使用它只是忽略文件头

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;