2011-12-05 87 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;