Topic: How to use find_or_initialize or find_or_create with validation?

My code

The logic looks like this:

Already have an Invite to this "email" from current_user?:

If not - create a new Invite, send an email (method deliver at model)
If he went there more than one day ago
     then update Invite and send a new mail AGAIN
     otherwise, notice: "Invite has been sent. Check the spam folder or wait for another day".

Model Invite works OK. Check this val

  def ensure_user_can_resend_invites
    if !new_record? || updated_at > 1.day.ago
      errors.add(:email, :taken)
    else
      message_will_change!
    end
  end

Please, check 'create' method. It's not work right.

  def create
    @invite = current_user.invites.find_or_initialize_by_email(params[:invite][:email]).update_attributes(params[:invite])

    respond_to do |format|
      if @invite.save
        format.html   { redirect_to account_invites_path, notice: "Приглашение пользователю #{@invite.email} отправлено!" }
        format.mobile { redirect_to account_invites_path }
      else
        format.html   { render action: 'index' }
        format.mobile { render action: 'index' }
      end
    end
  end

I use "find_or_create_by_email". If find exists Invite, I need "save" this and notice user. If create new Invite, I dont need "save", but user must be notice also!

I use "find_or_initialize_by_email".
If initialize - save true. If find exists Invite - save false!

How to be notice condition? How to use find_or_create with Model validation for updated_at? (validator "ensure_user_can_resend_invites")

Last edited by foxweb (2012-08-16 08:19:59)