将控制从一个控制器传递到另一个控制器

时间:2015-09-12 14:21:52

标签: ruby-on-rails rss

我希望通过我的rails应用程序从RSS中获取文章。我有一个网页,其中有一个按钮,可以执行这些文章的抓取。有一个User和Article模型,我已经定义了控制器来抓取这些文章。这些抓取控制器应从RSS提要中获取值并将值传递给Article控制器。

我是rails的新手,我不确定如何执行此操作。以下是我到目前为止所做的工作。

class ArticlesController < ApplicationController
  def create
    @article = Article.new(article_params)
    @article.user = current_user
    respond_to do |format|
      if @article.save
        format.html { redirect_to rss_importer_path }
        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


  private
    def set_article
      @article = Article.find(params[:id])
    end

    def article_params
      params.require(:article).permit(:author, :title, :summary, :url, :date, :image, :user_id)
    end
end

class RssImportersController < ApplicationController
  def scrape
    url = 'http://tviview.abc.net.au/rss/category/abc1.xml'
    open(url) do |rss|
      feed = RSS::Parser.parse(rss)
      feed.items.each do |item|
        article_path(author => nil, title => item.title, summary => item.description,
                 source => item.link, date => item.pubDate, image => nil)

      end
    end
  end


end

在routes.rb -

  resources :rss_importers

这是我的观点 -

<div class="btn-group pull-left" role="group">
  <%= link_to 'Scrape Articles', rss_importer_path ,class: "btn btn-default" %>
</div>
<br> <br>

<h1>All Articles</h1>

<% @articles.each do |article| %>
<%= render partial: 'index_article', locals: {article: article} %>
<% end %>

1 个答案:

答案 0 :(得分:0)

我建议不要使用控制器进行刮擦。您可以创建一个服务类,只需从文章控制器中调用它。

在app / services / rss_importer.rb中:

class ImportRss
  def call(params)
    #Import code here
   end
end

然后在你的文章控制器中:

def create
  result = ImportRss.new.call(params)
  #Rest of your codes
end

以下是关于如何使用服务类的好文章:http://adamniedzielski.github.io/blog/2014/11/25/my-take-on-services-in-rails/

相关问题