ruby-on-rails - 如何在链接中传递参数 - ruby​​ on rails

标签 ruby-on-rails ruby

我应该如何传递有关文章类别的参数。我有一篇属于文章类别的文章。当我点击这个 <%= link_to @article.name, article_categories_path%> , 我想查看该类别中的所有文章。所以我必须将参数通过它传递给 ArticleCategoryController。我的声明链接是否正确?现在我得到一个“文章”而不是类别名称(当我点击它时我收到错误:Document.find expects the parameters to be 1 or more ids,)。

文章模型

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

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

  belongs_to :user
  #kategorie
  belongs_to :article_category

文章 Controller

  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

文章分类模型

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

文章分类 Controller

class ArticleCategoriesController < ApplicationController

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

文章 View

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

最佳答案

我通常做这样的事情的方式是有很多通过。 (我也会检查你的模型,因为看起来你有 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 %>

随心所欲地格式化。这假设您的 route 有一个 resources :categories,并且 Category 有一个名称字段

关于ruby-on-rails - 如何在链接中传递参数 - ruby​​ on rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32509590/

相关文章:

ruby-on-rails - 如何根据操作使 before_filter 函数表现不同?

ruby-on-rails - Ruby on Rails 与 sql server

ruby 哈希 : how to filter value (an array) and return?

ruby - 如何检测客户端是否关闭 Rails 4.2 上的连接

ruby - 如何引用当前线程

ruby-on-rails - 为 ruby​​ on rails 配置 Notepad++

ruby-on-rails - 如何创建这个 Ruby on Rails 表单?

ruby-on-rails - 如何防止 Ruby money 出现浮点错误

ruby-on-rails - has_secure_password 和电子邮件验证

ruby - 使用正则表达式找到一个字符串,然后使用正则表达式找到一个新的字符串来替换它