在我的Ruby on Rails 3.2.3应用程序中,我有两个模型通过has_many关系通过第三个模型连接:
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
相关联。但是,必须指定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
个实例。但是,使用<<
运算符时,在连接表上指定属性的更优雅方法是什么?
答案 0 :(得分:0)
我认为您正在尝试使用不属于那里的信息更新角色表。在您的情况下,角色名称应包含在组织或用户中,而不是您的连接表中。要么包含在父模型中,要么包含更好,请创建另一个连接表,以便您可以将角色与用户连接。
class role_users < ActiveRecord::Base
attr_accessible :user_id, role_id
belongs_to :user
belongs_to :role
end
class Roles < ActiveRecord::Base
attr_accessible :title, :foo, :bar
has_many :role_users
has_many :users, :through => :role_users
end
class Users < ActiveRecord::Base
attr_accessible :other, :foo, :bar
has_many :role_users
has_many :roles, :through => :role_users
end
然后像我们一样自己设置这些角色,并添加一个复选框或下拉,以便用户可以选择。或者让用户自己输入信息。