Ken W
Ken W

Reputation: 962

Rails: Specify custom action based on failed activeRecord save

class Subscription < ActiveRecord::Base
  validates :feed_id, presence: true, uniqueness: true

now that I verify that a user cannot subscribe to the same feed twice as per the above code, I would like to specify in a notice that they are already subscribed to the feed. How can I go about specifying a condition if the validation fails, sending a notice other than the generic "Subscribe was unsuccessful"

class SubscriptionsController < ApplicationController
def new
#do things
    if @subscription.save
      redirect_to reader_url, notice: "You are now subscribed to: "+feed.title
    else
      redirect_to reader_url, notice: "Subscribe was unsuccessful!"
    end
  end

Upvotes: 0

Views: 90

Answers (1)

x1a4
x1a4

Reputation: 19485

If there was a validation failure, it will populate @subscription.errors, which you can inspect and show messages from as needed.

Upvotes: 2

Related Questions