Rails + Nokogiri:控制器创建

Rails + Nokogiri : controller create

我正在创建一个 simple_form,允许用户通过向原始文章提供 link 在我的数据库中创建新文章。如果用户提供 URL ("original_url"),我将使用 Nokogiri 来获取信息。

我收到以下错误消息:"no implicit conversion of nil into String",它告诉我来自字段 "original_url" 的 simple_form 输入不可用于控制器 / Nokogiri。

是否可以在保存之前使用 simple_form 中的变量?

我的控制器 - 创建代码:

def create
  if @original_url = nil
    @article = Article.new(article_params)
  else
    @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 = Article.new(:headline => headline)
  end

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

我应该用另一种方式调用 "original_url" 变量吗?

首先,您在第一个条件中使用赋值:

if @original_url = nil

所以 @original_url 总是变成 nil 并且条件永远不会为真。这是一个典型的错误。

这就是您在 Ruby 中检查 nil 的方式:

if @original_url.nil?

现在,@url 为零的原因很可能是在您的参数中,您有 article root。在这种情况下,你需要写:

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