ユーザーとプロジェクトの 2 つのクラスがあります。ユーザーは多くのプロジェクトを所有でき、プロジェクトは多くのユーザーが所有できます。ただし、プロジェクトには少なくとも 1 人のユーザーが必要ですが、ユーザーは必ずしもプロジェクトを持っている必要はありません。
これは私が現在持っているものです:
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
したがって、プロジェクトを作成する前に、まずユーザーが存在する必要があります。私が現在問題を抱えているのは、新しいプロジェクトを作成して新しいプロジェクトにユーザーを追加しようとすると、ユーザーが既にユーザーテーブルに存在するため、保存できないことです。より具体的には、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
ユーザーがユーザーテーブルに存在するかどうかを確認しながら、プロジェクトテーブルと所有権テーブルの両方に新しいエントリを作成して、新しいプロジェクトを既存のユーザーに関連付ける方法はありますか (新しいユーザーを作成しようとしません)。ありがとう!