在我的 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
我想将 aUser
与Organization
. 但是,需要指定title
上的属性Role
。为了强制执行这一点,我在 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
直接创建一个实例。但是,在使用运算符时,在连接表上指定属性的更优雅的方法是什么<<
?