Rails HABM文章和类别,无法获取类别链接以查看相关文章

时间:2014-08-05 20:22:54

标签: ruby-on-rails ruby-on-rails-4

我正在创建一个新闻网站,并创建了具有belongs_to_and_have_many关联的文章和类别模型。

class Category < ActiveRecord::Base
  has_and_belongs_to_many :articles

    validates :name, presence: true, length: { in: 2..20 }, uniqueness: true

  def to_s
    "#{name}"
  end
end


class Article < ActiveRecord::Base
  has_many :comments
  has_and_belongs_to_many :categories
end

我创建了连接表

create_table "articles_categories", id: false, force: true do |t|
    t.integer "article_id"
    t.integer "category_id"
  end

现在,我设法在索引和显示网站上显示文章和所属类别。我想制作类别链接,指向与单个类别相关联的文章的网站(e.x. sport =&gt;所有具有该类别的文章)。在categories-index.html.erb中:

<h1>Categories</h1>

<div class="row">
  <% @categories.each do |category| %>

    <div class='col-sm-3'>
      <h2><%= link_to category %></h2>

      <h3>Articles</h3>
        <% category.articles.each do |article| %>
          <%= link_to article.title, article %>
        <% end %>
    </div>
  <% end %>
</div>

链接显示在网站上,但它们不会路由到任何内容。如何将这些链接路由到适当的站点?

class CategoriesController < ApplicationController
  def index
    @categories = Category.all
  end


  def show
  end

  def new
    @category = Category.new
    @articles = Article.all
  end

  def edit
    @articles = Article.all
  end

  def create
    @category = Category.new(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to @article, notice: 'Category added' }
        format.json { render :show, status: :created, location: @article }
      else
        format.html { redirect_to @article, notice: 'Category not added'}
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @category.update(category_params)
        format.html { redirect_to @category, notice: 'Category was successfully updated.' }
        format.json { render :show, status: :ok, location: @category }
      else
        format.html { render :edit }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

   def destroy

    @category.destroy
    redirect_to article_path(@article)
  end
  private
    def category_params
      params.require(:category).permit(:name, :article_ids => [])
    end
end

1 个答案:

答案 0 :(得分:0)

link_to助手至少需要两个参数,即要显示的内容和要路由的位置。

您的类别链接不包含后者

<%= link_to category %>

根据您希望链接的去向,尝试类似这样的内容

<%= link_to category.name, category %>

这将链接到CategoriesController#show操作。在该操作中,如果要显示给定类别的文章,可以在控制器中包含类似的内容

# CategoriesController
def show
  @category = Category.find(params[:id])
  @articles = @category.articles
end