1

私はこの2つのモデルがあるシンプルなアプリに取り組んでいます:

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

require_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 に答える