2015-09-10 36 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

相关问题