2013-10-13 58 views
0

我爲我們的文章實現標記系統。帶關係的標記系統

class Country < ActiveRecord::Base 
    has_many :articles 


end 


class Region < ActiveRecord::Base 
    has_many :articles 


end 


class Article < ActiveRecord::Base 

     belongs_to :region 
     belongs_to :country 

     def self.tagged_with(name) 
     Tag.find_by_name!(name).articles 
     end 

    end 

條控制器:

def index 
    if params[:tag] 
     @articles = Article.tagged_with(params[:tag]) 
     else 
     @region = Region.find(params[:region_id])   
     @article_region = @region.articles 
     end 
    end 

在我的索引頁我只顯示其與正確的區域params(region_id)相關的文章,所以這是正常工作。但是,我怎樣才能在「tagged_with」功能中整合區域和國家參數?

/en/italy/umbria/articles/wines>示出了標記爲「葡萄酒」並且具有與該區域布里亞

/en/italy/tuscany/articles/wines>示出了標記爲「葡萄酒」並且具有與該區域托斯卡納

的關係物品的關係的文章

/zh /意大利/文章/葡萄酒>顯示標籤爲「葡萄酒」,並與國家意大利有關的文章

回答

1

您有兩種選擇:nesting Your r資源和使用動態細分。檢查導軌導向:

http://guides.rubyonrails.org/routing.html#dynamic-segments

基本上可以這樣說:

# routes.rb, You should put this just before defining root path. Also test how it works with routes scopes/namespaces 
get ':country/:region/articles/:tag', to: "articles#tagged_and_regional" 

控制器:

#articles_controller.rb 
def tagged_and_regional 
    Article.tagged_and_regional(params[:country], params[:region], params[:tag]) 
end 

型號:

# I don't know Your data structure, so I am taking a guess 
def self.tagged_and_regional(country, region, tag) 
    joins(:region, :country, :tags) 
    .where("counties.name = ? AND regions.name = ? AND tags.name = ?", country, region, name) 
end