开发者

RoR - model relation

开发者 https://www.devze.com 2023-01-26 11:29 出处:网络
Hi have a table named category which has two foreign keys to the table user, structure is given below. How can I get the user name corresponding to created_by and modified_by by using relations. @cate

Hi have a table named category which has two foreign keys to the table user, structure is given below. How can I get the user name corresponding to created_by and modified_by by using relations. @category = Category.find(params[:id]) is giving only the details from the category table. My current model class is

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

How can I associate both the fields created_by and modified_by to the user model

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,
  `modif开发者_C百科ied_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;


This should work for you:

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

精彩评论

暂无评论...
验证码 换一张
取 消