gpt4 book ai didi

ruby-on-rails - 避免 `save!` on Has Many Through Association

转载 作者:行者123 更新时间:2023-12-03 20:21:00 24 4
gpt4 key购买 nike

我有一个 has_many 通过与属性的关联和对“连接模型”的一些验证。当我尝试做类似 @user.projects << @project 的事情时并且关联已经创建(因此唯一性验证失败),将引发异常而不是将错误添加到验证错误中。

class User 
has_many :project_users
has_many :projects, :through => :project_users

class Project
has_many :project_users
has_many :users, :through => :project_users

class ProjectUser
belongs_to :user
belongs_to :project


# ...
if @user.projects << @project
redirect_to 'somewhere'
else
render :new
end

我怎样才能像使用 << 那样创建关联?方法,但调用 save而不是 save!这样我就可以在我的表单上显示验证错误,而不是使用 rescue捕获这个并妥善处理?

最佳答案

我认为你做不到。来自API :

collection<<(object, …) Adds one or more objects to the collection by setting their foreign keys to the collection’s primary key. Note that this operation instantly fires update sql without waiting for the save or update call on the parent object.

If saving fails while replacing the collection (via association=), an ActiveRecord::RecordNotSaved exception is raised and the assignment is cancelled.

解决方法可能如下所示:

if @user.projects.exists? @project
@user.errors.add(:project, "is already assigned to this user") # or something to that effect
render :new
else
@user.projects << @projects
redirect_to 'somewhere'
end

这将使您能够在关联已存在的地方捕获失败。当然,如果对关联的其他验证可能失败,您仍然需要捕获异常,因此它可能不是很有帮助。

关于ruby-on-rails - 避免 `save!` on Has Many Through Association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com