我试图在主页上显示我的轮播和索引。我在我的.each循环中遇到了无方法错误,但我似乎无法追查问题。这是我的代码请帮助= /。当我遵循最近的教程时,一切看起来都是正确的。
显示/Users/prestonphan/Desktop/My_Portfolio/app/views/posts/_index.html.erb第1行:
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all.order('created_at DESC')
end
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
_index.html.erb
<% @posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime['%B, %d, %Y']%></p>
</div>
<% end %>
home.html.erb
<div class="jumbotron center">
<h1>Eggsix</h1>
<p>dozens by the half</p>
</div>
<%= render 'static_pages/carousel'%>
<%= render 'posts/index'%>
答案 0 :(得分:1)
如果你想重新使用一些视图,那就做一个像这样的部分(添加像_post.html.erb
这样的部分来渲染单个项目会更方便,但为了你的理解,我让解决方案更简单了):
应用/视图/帖/ _posts.html.erb 强>
<% posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime['%B, %d, %Y']%></p>
</div>
<% end %>
然后,在 app / views / posts / index.html.erb 中,只需调用部分渲染,提供一系列帖子:
<%= render partial: 'posts/posts', locals: { posts: @posts } %>
app / views / static_pages / home.html.erb 相同,请添加:
<%= render partial: 'posts/posts', locals: { posts: @posts } %>
但@posts
个nil
变量的home
变量为home
,因此您应该在StaticPagesController
的{{1}}行动中获取帖子:
class StaticPagesController < ApplicationController
def home
@posts = Post.all.order('created_at DESC')
end
end
多数民众赞成。希望这对你有意义。