0

I want to check to see if a feed I retrieve based on a user-specified url is nil, but I can't seem to find a good way to handle this.

I feel the best way to handle it would be to set a custom ActiveRecord error upon checking via if statement like I've added in the code below. But then how do I force the save to fail? The code needs access to the feed_url so that I can validate it's either nil or returns 404 etc...

# POST /feeds
  # POST /feeds.json
  def create
    @feed = Feed.new(params[:feed])
    feed = Feedzirra::Feed.fetch_and_parse(@feed.feed_url)

    if(feed) #what to do here?? the below doesn't work if feed returns as nil or fixnum

      @feed.title = feed.title
      @feed.author = feed.entries.first.author
      @feed.feed_url = feed.feed_url
      @feed.feed_data = feed
    end

    respond_to do |format|
      if @feed.save
        format.html { redirect_to reader_path, notice: 'Feed was successfully created.' }
        format.json { render json: @feed, status: :created, location: @feed }
      else
        format.html { render action: "new" }
        format.json { render json: @feed.errors, status: :unprocessable_entity }
      end
    end
  end
Ken W
  • 962
  • 4
  • 12
  • 19

1 Answers1

0

You can use before_save callback in your model.

class Feed < ActiveRecord::Base
 before_save :check_model

def check_model
  if condition == True
    #Execute true statement
  else
    # raise error
end

Thanks

Paritosh Singh
  • 6,288
  • 5
  • 37
  • 56
  • Turns out that before_validation is the correct one if the code doesn't need access to a specific instance variable. The correct solution ended up being validate do |feed| feed.errors.add(:base, "Looks like that's not a valid feed, or the feed is not working!") unless !!feed.feed_data end – Ken W Sep 20 '12 at 04:37