nil的未定义方法`articles':NilClass当我试图在我的文章显示页面上显示相关文章时

时间:2017-10-03 20:04:51

标签: ruby-on-rails ruby tags ruby-on-rails-5

朋友您好我有这个错误我昨天在我的Rails应用程序上遇到过。当我试图在我的文章显示页面上显示相关文章时,我得到nil的未定义的方法`文章':NilClass。

这是我的应用代码

tag.rb

void HandleDeleter(HANDLE h)
{
    if (h) CloseHandle(h);
}

tagging.rb

UniHandle = unique_ptr<void, function<void(HANDLE)>>; 

articles_controller

class Tag < ApplicationRecord
  has_many :taggings
  has_many :articles, through: :taggings

  def to_s
    name
  end

end

文章show.html.erb

class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :article
end

代码控制器

class ArticlesController < ApplicationController
 before_action :find_article, only: [:show, :edit, :update, :destroy]
 before_action :owned_article, only: [:edit, :update, :destroy]
 before_action :authenticate_user!, except: [:index, :show]

def index
 @articles = Article.all.order("created_at desc")
end

def show
end

def new
  @article = current_user.articles.build
end

def create
  @article = current_user.articles.build(article_params)

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

def edit
end

def update
  if @article.update(article_params)
    redirect_to @article, notice: "Your article was successfully updated!"
  else
    render 'edit'
  end
end

def destroy
  @article.destroy
  redirect_to articles_path
end

private

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

def article_params
  params.require(:article).permit(:title, :content, :image, :tag_list)
end

def owned_article
  unless current_user == @article.user
    flash[:alert] = "That article does not belong to you!"
    redirect_to root_path
  end
end

显示标记视图

<div class="container">
<div class="row text-white text-center">
    <div class="col-md-10 col-lg-10 ml-sm-auto mr-sm-auto article-show-col">
        <br>
        <h1><%= @article.title %></h1>
        <p class="text-muted">Posted on: <%=       @article.created_at.strftime('%-b %-d, %Y') %></p>

        <p>
          Tags:
          <% @article.tags.each do |tag| %>
            <%= link_to tag.name, tag_path(tag) %>
          <% end %>
        </p>


        <!-- <br> -->
        <div class="article-show-image">
            <%= image_tag @article.image.url(:wide) %>
        </div>
        <!-- <br> -->
        <p><%= @article.content.html_safe %></p>

        <hr class="index-hr">

        <h5>Broadcast this article</h5>

        <%= social_share_button_tag("Hey! Checkout this new article from TWM!") %>

        <hr class="index-hr">

        **<h5>Related Articles</h5>
        <% @tag.articles.each do |article| %>
            <li><%= link_to article.title, article_path(article) %></li>
        <% end %>**

        <div class="btn-group">
            <%= link_to "Back", articles_path, class: "btn-custom btn-sm" %>
            <% if user_signed_in? %>
                <% if @article.user_id == current_user.id %>
                    <%= link_to "Delete", article_path(@article), method: :delete, data: { confirm: "Are you sure you want to delete this article?" }, class: "btn-custom btn-sm" %>
                    <%= link_to "Edit", edit_article_path, class: "btn-custom btn-sm" %>
                <% end %>
            <% end %>
        </div>
    </div>
</div>

谢谢!

3 个答案:

答案 0 :(得分:1)

这是一个较长的答案,可以解决您的问题。问题是,您希望让所有articles与您展示的tag共享article,而大概不会在相关文章列表中显示当前文章。我会通过向您的related_articles模型添加Article方法并在您的视图中调用它来实现此目的。

将以下方法添加到app/models/article.rb

def related_articles
    Article.joins(:tags).where(tags: { id: self.tags.pluck(:id) }).where.not(id: self.id)
end

上述查询应返回所有具有匹配标记的文章,同时排除自身。

您现在可以使用以下命令替换视图中的相关文章部分:

**<h5>Related Articles</h5>
<% @article.related_articles.each do |article| %>
    <li><%= link_to article.title, article_path(article) %></li>
<% end %>**

最后一个注意事项与您的问题并不严格相关,但值得一提。通过迭代@article.tags,您的视图正在创建N + 1查询。这些效率非常低。好消息是,只需更改find_articles中的articles_controller方法,就可以使用eager loading修复此问题,如下所示:

def find_article
  @article = Article.includes(:tags).find(params[:id])
end

可能有一种更有效的方式来编写related_articles查询,但这应该有效。

编辑:

另一种编写related_articles查询的方法如下。这将产生相同的结果。它将更多的处理移动到数据库,从而减少对数据库的调用。

def related_articles
    Article.distinct.joins(tags: :articles).where.not(id: self.id)
end

答案 1 :(得分:0)

您的ArticlesController在显示视图中使用时不会实例化@tag变量。

答案 2 :(得分:0)

show.html.erb中,您正在尝试:

<div class="container">
  <div class="row text-white text-center">
    <div class="col-md-10 col-lg-10 ml-sm-auto mr-sm-auto article-show-col">

      ...

      <% @tag.articles.each do |article| %>
          <li><%= link_to article.title, article_path(article) %></li>
      <% end %>**

      ...

    </div>
  </div>
</div>

但是,嘿,看看吧! @tag行动中没有show

class ArticlesController < ApplicationController
  before_action :find_article, only: [:show, :edit, :update, :destroy]
  before_action :owned_article, only: [:edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  ...

  def show
    #look! no @tag
  end

  ...

end