0

我有两个类用户和项目。一个用户可以拥有多个项目,一个项目可以由多个用户拥有。但是,一个项目必须至少有一个用户,而一个用户不一定必须有一个项目。

这是我目前拥有的:

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

有没有办法将新项目与现有用户关联,在项目表和所有权表中创建一个新条目,同时检查用户是否存在于用户表中(而不是尝试创建新用户)?谢谢!

4

2 回答 2

0

尝试将您对ownership课程的验证更改为

validates :user, presence: true
validates :project, presence: true

不确定验证实际关联 ( project) 与 id ( project_id) 的区别是否会有所不同,但值得尝试。也就是说,如果您是从项目端创建关联(并且项目必须始终有一个用户,而不是其他方式),那么根据您的业务规则,您实际上只需要验证的用户端。

于 2013-04-18T12:11:11.653 回答
0

您的项目的所有权记录是无效的,因为它需要存在一个project_id,这是nil一个新项目。您需要先创建项目或更改Ownership模型中的验证。

您可以通过检查所涉及模型的错误对象来看到这一点:

> prj.errors.full_messages
=> ["Ownerships is invalid"]
> prj.ownerships.first.errors.full_messages
=> ["Project can't be blank"]
于 2013-04-18T03:24:18.933 回答