开发者

Rails 3 - Form Validation - Moving Logic to an Callback or Observer?

Hey all, I'm having issues with validation that I've been working on the last couple of days with no luck. What I have is that I have a model that requires the user to input a URL. I've done this with the following in my model:

validates :url, :presence => true  

When a user submits their form, I take their URL and open it with Nokogiri to pull basic things like the webpage title. I'm currently doing this with my Create method in the controller. Code looks like so:

def create
    require 'open-uri'
    @page = Page.new(params[:page])

doc = Nokogiri::HTML(open(@page.url))

The problem I run in to, is that if the user enters a blank form, Nokogiri will error out as it runs even though I've tried to validate the form.

My question is, should I be moving this sort of logic to a callback or an observer? I'm pretty new to rails but would there be a way for me to work with my data/instance variables from a callback/observer? I've failed simply using @page, but was wondering if there was a way I'm supposed to pass it into the callback/observer if this is where this sort of logic is supposed to be开发者_开发问答 placed?

Thanks


Would be better to put this in the model.

Controller method does something like

def create
  @page = Page.new(params[:page])
  respond_with @page
end

and in the model you have

class Page < ActiveRecord::Base
  ...
  before_save :pull_info_from_url

  def pull_info_from_url
    doc = Nokogiri::HTML(open(self.url))
    ...
  end
end

the before_save callback is run after validations, so if the presence-check fails, this code doesn't get executed, and the form with errors is shown instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜