bymannan
bymannan

Reputation: 1383

Rails: How to receive errors from nested models

I am trying to validate emails given from a CSV list of emails. So I have created the invite_list virtual attribute where when given a list of emails, it will loop and create a new record in the invited_only_emails model.

Now the thing is, this works fine, but how can I catch the validation error thrown by InvitedOnlyEmail while looping in Users model so I'll be able to use that error in the controller?

This is my main model:

class Users < ActiveRecord::Base
attr_accessor :invite_list
attr_accessible :invite_list

has_many :invited_only_emails

  def invite_list=(list)
    list.split(",").each do |address|
        self.invited_only_emails.create! :email => address
      end
  end

  def invite_list
    self.invited_only_emails.map {|email| email.email}.join(',')
  end
end

And this is the invited_only_emails model:

class InvitedOnlyEmail < ActiveRecord::Base
  attr_accessible :email
  belongs_to :users

  validates_format_of :email, :with => /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i

end

Thanks!

Upvotes: 0

Views: 40

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51151

I think you could use validates_associated method:

class User < ActiveRecord::Base
  validates_associated :invited_only_emails
  # ...
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_associated

Upvotes: 1

Related Questions