Ruby on rails 防止Rails中的重复关联记录

Ruby on rails 防止Rails中的重复关联记录,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,associations,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Associations,我正在开发一个简单的应用程序,其中有两种型号: class Report < ActiveRecord::Base attr_accessible :comments, :user_attributes belongs_to :user accepts_nested_attributes_for :user end class User < ActiveRecord::Base attr_accessible :username has_many :re

我正在开发一个简单的应用程序,其中有两种型号:

class Report < ActiveRecord::Base
  attr_accessible :comments, :user_attributes

  belongs_to :user

  accepts_nested_attributes_for :user
end 

class User < ActiveRecord::Base
  attr_accessible :username

  has_many :reports
end 
表单发送此JSON参数:

{ user_attributes => { :username => "superuser" }, :comments => "Sample comment 1." }
简单报表控制器处理记录报表和用户的创建

def create
  @report = Report.new(params[:report])
  @report.save
end

这将成功地同时创建一个报告和一个用户。如果我提交另一个具有相同用户名(超级用户)的报告,我需要做的是防止创建另一个用户。在Rails模型或控制器中是否有一种简单的方法来实现这一点?谢谢。

您可以使用reject\u if选项拒绝用户创建

accepts_nested_attributes_for :user, reject_if: Proc.new { |attributes| User.where(username: attributes['username']).first.present? }
我会将其重构为:

accepts_nested_attributes_for :user, reject_if: :user_already_exists?

def user_already_exists?(attributes)
  User.where(username: attributes['username']).first.present?
end

一个用户可以提交多个报告吗?如果这当前创建了一个新用户,我会感到惊讶,除非发生了其他事情。现在您正在实例化一个新报告并保存它,但我没有看到它保存一个用户类。编辑-这是我不知道的Rails魔法吗?@John是的。用户名可以在发送报告时多次使用。@保存用户的BrianKung代码不是必需的,因为它是由Rails关联处理的。@BenAluan啊,错过了的接受嵌套属性,\u,抱歉。
accepts_nested_attributes_for :user, reject_if: :user_already_exists?

def user_already_exists?(attributes)
  User.where(username: attributes['username']).first.present?
end