2017-01-05 45 views
0

這些都是在同一個控制器操作:我該如何幹這個控制器代碼?

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 

正如你可以看到這個代碼是很重複。這繼續了幾個更多的條目。有沒有辦法幹這件事?是否有可能或建議創建某種塊功能?

回答

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,但它是完全值得的。

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

用它查看: - 根據您的選擇

<%= 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

+0

如何創建路線? 'example.com/news/world''example.com/news/politics'等 –

+0

我已更新該帖子。 –

+0

如果有人在url中鍵入'example.com/news/world',上面的代碼如何生成一個路由?我們從來沒有定義custom_method是什麼? –