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

标签 ruby-on-rails ruby-on-rails-3 validation activerecord has-many-through

我有一个 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/

相关文章:

ruby-on-rails - Join 子查询中的计数和求和 - 我可以使用 ActiveRecord 构建此 sql 查询吗?

ruby-on-rails - 将脚本 src 转换为 Rails 中的快速 '//= require' 语句

html - 如何让文本框侧面的按钮始终完美对齐?

hibernate - Spring MVC - Hibernate form :errors and bindingresult, jsp 不显示错误消息

jquery - 如何使用 jQuery.validate() 但依赖 native Chrome 验证警报?

ruby-on-rails - 如何使用 rspec stub 访问器

ruby-on-rails-3 - Rails Assets 管道测试通过生产中断

ruby-on-rails-3 - EngineYard 上的太阳黑子锁定问题

ruby-on-rails-3 - ActiveRecord .select():是否可以清除旧选择?

ruby-on-rails - 保存失败时的Rails日志模型错误