我怎么能干这个控制器代码?

时间:2017-01-05 04:56:56

标签: ruby-on-rails

这些是同一个控制器中的动作:

  def world
    @title = 'World'
    @regional = @articles.world.paginate(page: params[:reg_page], per_page: 6) 
      respond_to do |format|
        format.html { render 'index_region' }
        format.js { render :file => "articles/latest.js.erb" }
      end  
  end   

  def politics
    @title = 'Politics'
    @regional = @articles.politics.paginate(page: params[:reg_page], per_page: 6)
      respond_to do |format|
        format.html { render 'index_region' }
        format.js { render :file => "/articles/latest.js.erb" }
      end 
  end

  def sports
    @title = 'Sports'
    @regional = @articles.sports.paginate(page: params[:reg_page], per_page: 6)
      respond_to do |format|
        format.html { render 'index_region' }
        format.js { render :file => "/articles/latest.js.erb" }
      end 
  end

正如您所看到的,此代码非常重复。这还有几个条目。有没有办法干这个?是否有可能或建议创建某种块功能?

2 个答案:

答案 0 :(得分:1)

编辑控制器: -

  def custom_method
    @title = params[:title]
    if @title== 'World'
      @regional = @articles.world.paginate(page: params[:reg_page], per_page: 6) 
    elsif @title = 'Politics'
      @regional = @articles.politics.paginate(page: params[:reg_page], per_page: 6) 
    elsif @title = 'Sports'
      @regional = @articles.sports.paginate(page: params[:reg_page], per_page: 6) 
    end
      respond_to do |format|
        format.html { render 'index_region' }
        format.js { render :file => "articles/latest.js.erb" }
      end  
  end

title作为参数传递给链接。

routes.rb: -

get 'news/custom_method' => 'articles#custom_method'

这会生成news_custom_method_path

的链接

在View中使用它: -

<%= link_to "World", news_custom_method_path(id: articles.id, title: "World") %>
<%= link_to "Politics", news_custom_method_path(id: articles.id, title: "Politics") %>
<%= link_to "Sports", news_custom_method_path(id: articles.id, title: "Sports") %>

您可以根据您的选择重命名custom_method

答案 1 :(得分:1)

我不想在这里提出任何错误的想法,而不是深入研究你的项目,但是根据我的经验(and apparently also in DHHs opinion),坚持在控制器中使用RESTfull资源总是一个好主意。

基本上你的政治/体育/世界方法所做的是展示更具体的文章实例,对吗?那么你可以做的是(坚持使用REST)有一个像这样的索引方法:

def index
  category  = params[:category] || "all"
  @title    = category.humanize
  @regional = @articles.send(category).paginate(page: params[:reg_page], per_page: 6)

  respond_to do |format|
    format.html { render 'index_region' }
    format.js { render :file => "/articles/latest.js.erb" }
   end 
 end

在所有操作中渲染相同的模板是一个非常强烈的提示,您应该在一个方法中使用它们。您必须重写其他代码才能使用articles?category=sports资源,而不是articles/sports,当然,这非常值得。

相关问题