【问题标题】:RoR - model relationRoR - 模型关系
【发布时间】:2010-11-22 04:53:46
【问题描述】:

你有一个名为 category 的表,它有两个表用户的外键,结构如下所示。如何通过关系获取 created_by 和 modified_by 对应的用户名。 @category = Category.find(params[:id]) 仅提供类别表中的详细信息。我当前的模型类是

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;

【问题讨论】:

    标签: ruby-on-rails model associations relationship


    【解决方案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
    

    【讨论】:

    • 太好了!我需要第二部分(代码放在用户模型中)吗?
    • &lt;%= debug(@category.creator) %&gt; 显示所有字段,包括密码,有什么方法只检索用户名字段?
    • 你不需要需要第二部分,但你应该拥有它。定义双方的关系总是最好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多