1

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

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 

我也有这个 HAML 新报告视图:

= form_for @report do |f|
  .field
    = f.fields_for :user do |u|
      = u.label :username
      = u.text_field :username
  .field
    = f.label :comments
    = f.text_area :comments

  .action
   = f.submit "Submit report"

表单发送此 JSON 参数:

{ user_attributes => { :username => "superuser" }, :comments => "Sample comment 1." }

简单报表控制器处理记录报表和用户的创建。

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

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

4

1 回答 1

2

您可以使用 reject_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
于 2013-03-24T03:19:23.457 回答