【发布时间】:2012-11-22 08:43:53
【问题描述】:
在我的 Ruby on Rails 3.2.3 应用程序中,我有两个模型通过 has_many through 关系通过第三个模型连接:
class Organization < ActiveRecord::Base
attr_accessible :description, :name
has_many :roles, dependent: :destroy
has_many :members, through: :roles, source: :user
end
class Role < ActiveRecord::Base
attr_accessible :title
belongs_to :organization
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :email, :fullname
has_many :roles, dependent: :destroy
has_many :organizations, through: :roles
end
我想将User 与Organization 相关联。但是,需要指定Role 上的title 属性。为了强制执行此操作,我在 MySQL 中将 title 字段设置为 NOT NULL。
以下是 Rails 控制台上发生的情况:
>> o = Organization.first
>> u = User.first
>> o.members << u
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO `roles` (`created_at`, `organization_id`, `title`, `updated_at`, `user_id`) VALUES ('2012-11-22 08:37:23', 1, NULL, '2012-11-22 08:37:23', 1)
Mysql2::Error: Column 'title' cannot be null: INSERT INTO `roles` (`created_at`, `organization_id`, `title`, `updated_at`, `user_id`) VALUES ('2012-11-22 08:37:23', 1, NULL, '2012-11-22 08:37:23', 1)
(0.1ms) ROLLBACK
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'title' cannot be null: INSERT INTO `roles` (`created_at`, `organization_id`, `title`, `updated_at`, `user_id`) VALUES ('2012-11-22 08:37:23', 1, NULL, '2012-11-22 08:37:23', 1)
from /path/...
我知道我可以直接创建一个Role 实例。但是,在使用 << 运算符时,在连接表上指定属性的更优雅的方法是什么?
【问题讨论】:
-
你为什么不在模型中使用验证存在而不是在数据库中放置 not null?
-
我在
Role中有validates_presence_of :title。它在模型级别和数据库级别都强制执行。但是,Rails 仍然会吐出 MySQL 错误,而不是一些验证错误。 -
你能从数据库中删除验证,看看会发生什么吗?
-
另外,如果不同的角色或固定的数量,你可能有很多吗?例如,管理员、帐户、员工?
-
在这种情况下,
title可以是任何东西(“副总裁”、“财务主管”等)。我坚信数据库效率,包括将字段定义为NOT NULL并具有外键,因此我不想从数据库中删除声明。
标签: ruby-on-rails ruby-on-rails-3 activerecord