使用link_to将路径显示为链接

时间:2015-07-08 18:16:35

标签: html ruby-on-rails link-to

我正在使用<% @articles.each do |article| %> do显示所有正在运作的文章,但它也会显示&#39; / subs / 27 / articles&#39;作为其中一篇文章。当我点击它时,它会进入我的索引视图。为什么此链接显示所有文章

Image

```

class SubsController < ApplicationController


  def show
    @sub = Sub.find(params[:id])
    @category = Category.find(params[:category_id])
    @articles = @sub.articles
    @article = @sub.articles.build
  end

  def new
    @category = Category.find(params[:category_id])
    @sub = Sub.new
  end


  def create
    @category = Category.find(params[:category_id])
    @sub = Sub.new(params.require(:sub).permit(:title))
    @sub.category = @category
    if @sub.save
        flash[:notice] = "Subcategory was saved"
        redirect_to [@category, @sub]
    else
        flash[:error] = "The Subcategory could not be saved"
        render :new
    end
  end
  def edit
    @category = Category.find(params[:category_id])
    @sub = Sub.find(params[:id])  
  end

  def update
    @category = Category.find(params[:category_id])
    @sub = Sub.find(params[:id])
    @sub.category = @category
    if @sub.update_attributes(params.require(:sub).permit(:title))
        flash[:notice] = "Subcategory was saved"
        redirect_to [@category, @sub]
    else
        flash[:error]= "The subcategory could not be saved"
        render :edit
    end
  end
  def sub_params
    params.require(:sub).permit(:title)
  end

views/subs/show.html.erb

<h1 align="center"><%= @sub.title %></h1>

<div class="row">
    <div class="col-md-8">
        <%=  link_to "Back", :back, class: "btn btn-default" %>
        <% if user_signed_in? %>
        <%= link_to "Edit", edit_category_sub_path(@category, @sub), class: "btn btn-success" %>
        <% else %>
        <% end %>

    </div>
    <!-- 
    <div class="col-md-4">
        <%= link_to "New Article", new_category_sub_path(@category), class: 'btn btn-success' %>
    </div>
-->
</div>
<hr>
<br>
<div class="row">
    <% @articles.each do |article| %>
    <div class="col-xs-3">
        <div class="tile" >
            <h5 align="center">
                <%= link_to article.title, [@sub, article] %>
            </h5>
        </div>
    </div>
    <% end %>
</div>

<% if user_signed_in? %>
<div class="col-md-12">
    <%= render 'articles/form', category: @category, article: @article, sub: @sub %>
</div>
<% else %>
<% end %>
    <!-- 
    <div class="col-md-12">
        <%= render 'articles/form', category: @category, article: @article, sub: @sub %>
    </div>
-->

```

1 个答案:

答案 0 :(得分:0)

在您向我提供更多信息后,

我认为这是你的问题:

@sub.articles.build

它正在构建一个新的未保存的文章关联,然后它会遍历文章,包括未保存的记录,因此标题为空。