2015-09-10 71 views
2

如何通過關於文章類別的參數。我有一篇文章屬於文章類別。當我點擊這個<%= link_to @article.name, article_categories_path%>,我想看看這個類別中的所有文章。所以我必須通過它將參數傳遞給ArticleCategoryController。我的聲明鏈接是否正確?現在我得到一個「文章」,而不是類別名稱(當我點擊它時,我收到錯誤:Document.find expects the parameters to be 1 or more ids,)。如何在鏈接中傳遞參數 - ruby​​ on rails

條模型

class Article 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :title, type: String 
    field :content, type: String 

    belongs_to :user 
    #kategorie 
    belongs_to :article_category 

第CONTROLER

class ArticlesController < ApplicationController 
    def article 
    @article = Article.order_by(created_at: 'desc').page params[:page] 
    end 

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

ArticleCategory模型

class ArticleCategory 
    include Mongoid::Document 
    include Mongoid::Timestamps 


    field :name, type: String 

    has_many :articles 


end 

ř歐特斯

resources :article_categories do 
    resources :articles, shallow: true 
    end 

ArticleCategories控制器

class ArticleCategoriesController < ApplicationController 

    def index 
    @category = ArticleCategory.find(params[:id]) 
    @articles = @category.articles 
    end 
end 

文章觀點

<p>Category: <%= link_to @article.name, article_categories_path%> 
      Tagi: <%= link_to "Tagi", tags_path %> </p> 
+0

你的路線是什麼樣的。 – Doon

+0

爲什麼你要在你的'link_to'中發送一個文章名作爲你的第一個參數?不知道你打算做什麼。 –

回答

0

<%= link_to "All", article_categories_path(@category) %>

只要你已經有了@Category變盤,這將帶你到/ article_categories /:id

1

我通常會做這樣的事情的方式是與一個有很多通過。 (還我會檢查你的模型,因爲它看起來像你有belongs_to的/向後的has_many,belongs_to的推移與外鍵的型號)..

class Article 
    has_many :article_categories 
    has_many :categories, through: :article_categories 
end 

class ArticleCategory 
    belongs_to: :article 
    belongs_to: :category 
end 

class Category 
    has_many :article_categories 
    has_many: articles, through: :article_categories 
end 

然後,如果你想看到在一個給定的所有文章類別。那麼你可以通過CategoriesController

class CategoriesController < ApplicationController 
    .... 
    def show 
     @category = Category.find params[:id] 
    end 

end 

然後你應該能夠通過@ category.articles關聯獲得所有文章。

既然你現在這樣做,你只會通過article_category表獲得1個類別。

在迴應置評..

每篇文章都將有多個類別..

所以,你會是這樣的。

<% @article.categories.each do |cat| %> 
    <%= link_to cat.name, cat %> <br /> 
<% end %> 

不管你想要的格式。假設你在你的路線中有resources :categories,並且Category有一個名稱字段

+0

好主意,所以現在我該如何鏈接到文章視圖中的類別? –

+0

更新後我越來越Mongoid問題: 我'無效選項:通過提供給關係:categories.' –

+0

啊看起來像mongoid不支持。 http://stackoverflow.com/questions/7000605/how-to-implement-has-many-through-relationships-with-mongoid-and-mongodb – Doon

相關問題