ruby-on-rails - Rails 5 - 未定义的局部变量或方法“post”
问题描述
我是 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
部分以显示在我的帖子文件夹中定义的帖子。
看起来问题与下面代码中的第一行有关,因为错误消息指向代码<li id="post-<%= post.id %>">
中_post.html.erb
:
<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
,我应该拥有与该类别相关的所有帖子。谁能帮我解决这个问题?
解决方案
您可能的意思是使用集合呈现部分:
render(partial: 'posts/post', collection: @category_posts)
在哪里应该扩展该部分以对每个帖子重复一次并分配局部post
变量。
obj
不是一个有效的参数,但object
如果你想用给定的对象渲染一次内容。