2010-11-22 89 views
0

您好有一个名为category的表,它有两个外键给表用户,结构如下。如何通过使用关系获取与created_by和modified_by相对应的用户名。 @category = Category.find(params[:id])仅给出类别表中的细节。我现在的模型类是RoR - 模型关系

class Category < ActiveRecord::Base 
    validates_uniqueness_of :title, :message => "Title already exist" 
    validates_presence_of :title, :message => "Cannot be blank" 
    belongs_to :user 
end 

我如何关联两个领域CREATED_BY和modified_by用户模型

CREATE TABLE IF NOT EXISTS `categories` (
    `id` int(11) unsigned NOT NULL auto_increment, 
    `title` varchar(255) NOT NULL, 
    `created_by` int(11) unsigned default NULL, 
    `modified_by` int(11) unsigned default NULL, 
    `created` datetime NOT NULL, 
    `modified` timestamp NOT NULL default CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `created_by` (`created_by`), 
    UNIQUE KEY `modified_by` (`modified_by`) 

CREATE TABLE IF NOT EXISTS `users` (
    `id` int(11) unsigned NOT NULL auto_increment, 
    `username` varchar(25) NOT NULL, 
    `password` varchar(255) NOT NULL, 
    `usertype_id` int(11) unsigned NOT NULL, 
    `active` tinyint(1) NOT NULL, 
    `created` datetime NOT NULL, 
    `modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `usertype_id` (`usertype_id`) 
) 


-- 
-- Constraints for table `categories` 
-- 
ALTER TABLE `categories` 
    ADD CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, 
    ADD CONSTRAINT `categories_ibfk_2` FOREIGN KEY (`modified_by`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE; 

回答

1

这应该为你工作:

class Category < ActiveRecord::Base 
    # ... 
    validates_uniqueness_of :title, :message => "Title already exist" 
    validates_presence_of :title, :message => "Cannot be blank" 
    belongs_to :creator, :foreign_key => 'created_by', :class_name => 'User' 
    belongs_to :editor, :foreign_key => 'modified_by', :class_name => 'User' 
    # ... 
end 

class User < ActiveRecord::Base 
    # ... 
    has_many :created_categories, :class_name => 'Category', :foreign_key => 'created_by'                     
    has_many :modified_categories, :class_name => 'Category', :foreign_key => 'modified_by' 
    # ... 
end 
+0

这就是伟大的!我是否需要第二部分(代码放置在用户模型中)? – 2010-11-22 05:16:13

+0

也''%= debug(@ category.creator)%>'显示所有字段包括密码,任何方式来检索用户名字段只? – 2010-11-22 05:17:35

+1

你不需要*第二部分,但你*应该*拥有它。它总是最好的定义双方的关系。 – Swanand 2010-11-22 05:42:58