Martin Clausen Martin Clausen - 1 year ago 101
Ruby Question

Rails + Nokogiri : controller create

I am creating a simple_form that allows users to create a new article in my database by providing a link to the original article. If the user provides a URL ("original_url"), I will use Nokogiri to fetch the information.

I get the following error message: "no implicit conversion of nil into String", which tells me that the simple_form input from the field "original_url" is not available to be used in the controller / Nokogiri.

Is it possible to use a variable from a simple_form before saving it?

My controller - create code:

def create
if @original_url = nil
@article =
@url = params[:original_url] #### I think this is where the problem is. How do I pass the "original_url" input into the controller? ####
data = Nokogiri::HTML(open(@url))
headline = data.at_css(".entry-title").text.strip
@article = => headline)

respond_to do |format|
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: @article }
format.html { render :new }
format.json { render json: @article.errors, status: :unprocessable_entity }

Should I call the "original_url" variable in another way?

Answer Source

First, you use an assignment in the first condition:

if @original_url = nil

So @original_url always becomes nil and the condition is never true. That's a classic mistake.

That's how you check for nil in Ruby:

if @original_url.nil?

Now, the reason why @url is nil is most likely that in your params, you have article root. In this case, you need to write:

@url = params[:acticle][:original_url]