0

我工作的一個簡單的應用程序在那裏我有這兩種型號:防止重複記錄相關Rails中

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模型或控制器中做到這一點?謝謝。

+0

用戶可以提交多份報告? – John 2013-03-24 02:45:32

+0

如果當前創建一個新用戶,除非有其他事情正在進行,否則我會感到驚訝。現在你正在實例化一個新的報告並保存它,但是我沒有看到它保存了一個用戶類。編輯 - 這是一些我不知道的Rails魔法? – 2013-03-24 03:06:41

+0

@John是的。用戶名可以多次用於發送報告。 – Ben 2013-03-24 03:11:40

回答

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 
+0

看起來像是在工作。需要重構一些測試。乾杯。 – Ben 2013-03-24 03:34:43