Reputation: 1368
I'm working on a simple app where I have this two models:
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
I also have this HAML new report view:
= 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"
The form sends this JSON parameters:
{ user_attributes => { :username => "superuser" }, :comments => "Sample comment 1." }
And the simple report controller handles the creation of the record report and user.
def create
@report = Report.new(params[:report])
@report.save
end
This successfully creates a report and a user at the same time. What I need to do is prevent the creation of another User if I submit another report with the same username (superuser). Is there an easy way to do this in Rails model or controller? Thank you.
Upvotes: 1
Views: 1320
Reputation: 4382
You can use the reject_if options to reject the user creation
accepts_nested_attributes_for :user, reject_if: Proc.new { |attributes| User.where(username: attributes['username']).first.present? }
I would refactor it to:
accepts_nested_attributes_for :user, reject_if: :user_already_exists?
def user_already_exists?(attributes)
User.where(username: attributes['username']).first.present?
end
Upvotes: 2