我有两个类用户和项目。一个用户可以拥有多个项目,一个项目可以由多个用户拥有。但是,一个项目必须至少有一个用户,而一个用户不一定必须有一个项目。
这是我目前拥有的:
class Project < ActiveRecord::Base
attr_accessible :prj_id, :name
has_many :ownerships, foreign_key: "project_id", dependent: :destroy
has_many :users, through: :ownerships
end
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation
has_many :ownerships, foreign_key: "user_id", dependent: :destroy
has_many :projects, through: :ownerships
validates :first_name, presence: true, length: { maximum: 25 }
validates :last_name, presence: true, length: { maximum: 25 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
end
class Ownership < ActiveRecord::Base
attr_accessible :project_id
belongs_to :user, class_name: "User"
belongs_to :project, class_name: "Project"
validates :user_id, presence: true
validates :project_id, presence: true
end
因此,在我们创建项目之前,用户必须首先存在。我目前遇到的问题是当我尝试创建一个新项目并将用户附加到新项目时,它不允许我保存,因为用户已经存在于 User 表中。更具体地说,在 rails 控制台中:
>> prj = Project.new(prj_id: 'hello', name: 'hello')
>> usr = User.find_by_id(1)
>> prj.users<<usr
>> prj.save
prj.save 行未能给出此消息:
(0.1ms) SAVEPOINT active_record_1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('example@example.com') AND "users"."id" != 1) LIMIT 1
(0.1ms) ROLLBACK TO SAVEPOINT active_record_1
=> false
有没有办法将新项目与现有用户关联,在项目表和所有权表中创建一个新条目,同时检查用户是否存在于用户表中(而不是尝试创建新用户)?谢谢!