【问题标题】:Rails 5 - undefined local variable or method `post'Rails 5 - 未定义的局部变量或方法“post”
【发布时间】:2018-10-25 15:40:29
【问题描述】:

我是 Rails 新手。我为我的帖子创建了一个类别模型,但是当我去显示与特定类别关联的所有帖子时,我得到一个 NameError 页面

这是我的类别show.html.erb 文件:

<h1> <%= "Category: " + @category.name %></h1>

<div align="center">
  <%= will_paginate @category_posts %>
</div>

<%= render 'posts/post', obj: @category_posts %>

<div align="center">
 <% will_paginate @category_posts %>
</div>

我正在渲染 _post.html.erb 部分以显示在我的帖子文件夹中定义的帖子。

看起来问题与下面代码的第一行有关,因为错误消息指向 _post.html.erb 代码中的 &lt;li id="post-&lt;%= post.id %&gt;"&gt;

<li id="post-<%= post.id %>">

  <span class="title"> <%=link_to post.title, post_path(post) %> </span>
  <span class="content"><%= truncate(post.content, length: 100) if post.content? %></span>
  <span class="content"> <%= image_tag post.picture.url if post.picture? %> </span>

  <span class="content">
    <% if post.category.any? %>
      <p><%= render post.category %></p>
    <% end %>
  </span>

</li>

这是我的category 控制器文件,我在其中确定了“显示”方法:

class CategorysController < ApplicationController
  before_action :require_admin, except: [:index, :show]

  def index
    @categories = Category.paginate(page: params[:page])
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      flash[:success] = "Category created successfully"
      redirect_to categories_path
    else
      render 'new'
    end
  end

  def show
    @category = Category.find(params[:id])
    @category_posts = @category.posts.paginate(page: params[:page], per_page: 5)
  end

后模型:

class Post < ApplicationRecord
belongs_to :user
  has_many :post_categories
  has_many :categories, through: :post_category

  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :user_id, presence: true
  validates :title, presence: true
  validate :picture_size

  private
    # validates the size of an upload picture
    def picture_size
      if picture.size > 5.megabytes
        errors.add(:picture, "should be less than 5MB")
      end
    end
end

一般的想法是,例如,当我转到localhost/categories/1 时,我应该拥有与该类别相关的所有帖子。 谁能帮我解决这个问题?

【问题讨论】:

  • 你有&lt;% render 'posts/post', obj: @category_posts %&gt;,应该是&lt;%= render 'posts/post', obj: @category_posts %&gt;。是不是笔误?
  • 这是一个错字。我忘了=
  • 我还没有使用 object 传入本地人的方式来处理部分内容。当部分路径中有目录时,它实际上是否按预期工作?

标签: ruby-on-rails ruby view ruby-on-rails-5 model-associations


【解决方案1】:

你可能是想渲染一个partial using a collection

render(partial: 'posts/post', collection: @category_posts)

应该在哪里扩展该部分以对每个帖子重复一次并分配本地 post 变量。

obj 不是有效参数,但object 是如果您想使用给定对象渲染一次内容。

【讨论】:

    猜你喜欢
    • 2015-12-26
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2014-07-06
    相关资源
    最近更新 更多