我有一个带帖子的简单博客应用程序。
我使用部分_post.html.erb
在我的索引页面中呈现帖子。
_post.html.erb
的div class=submission_details
与我的show
操作中使用的div _post.html.erb
相同。
如何将该部分分开,以便我可以在show.html.erb
部分和def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
页面中使用它?
posts_controller.rb
<%= render @posts %>
文章/ index.html.erb
<%= post.title %>
<div class="submission_details">
<%= time_ago_in_words(post.created_at) %>
<span id="submission_details_<%= post.id %>">
submitted by <%= link_to "#{post.user.name} (#{post.user.reputation_for(:points).to_i})", post.user %>
</span>
</div>
文章/ _post.html.erb
<%= @post.title %>
<%= @post.content %>
<div class="submission_details">
<%= time_ago_in_words(@post.created_at) %>
<span id="submission_details_<%= @post.id %>">
submitted by <%= link_to "#{@post.user.name} (#{@post.user.reputation_for(:points).to_i})", @post.user %>
</span>
</div>
文章/ show.html.erb
shared/submission_details
我尝试制作 <%= time_ago_in_words(@post.created_at) %>
<span id="submission_details_<%= @post.id %>">
submitted by <%= link_to "#{@post.user.name} (#{@post.user.reputation_for(:points).to_i})", @post.user %>
</span>
部分如下:
共享/ _submission_details.html.erb
show
由render 'shared/submission_details'
为index
操作呈现,但在index
操作中给了我nil。如何为{{1}}操作正确定义@post?
答案 0 :(得分:1)
部分地,您可以定义局部变量,当您渲染部分时,正确的语法将是:
render(partial: 'post_information', locals: { post: @post }
但可以缩写为
render('post_information', post: @post)
这是show动作,对于部分 _post.html.erb ,你的帖子实例不在变量 @post 上,而是在本地变量发布,所以你可以这样做:
render('post_information', post: post)
<强>文章/ index.html.erb 强>
<%= render @posts %>
<强>文章/ _post.html.erb 强>
<%= post.title %>
<div class="submission_details">
<%= render 'post_information', post: post %>
</div>
<强>文章/ show.html.erb 强>
<%= @post.title %>
<%= @post.content %>
<div class="submission_details">
<%= render 'post_information', post: @post %>
</div>
<强>文章/ _post_information.html.erb 强>
<%= time_ago_in_words(post.created_at) %>
<span id="submission_details_<%= post.id %>">
submitted by <%= link_to "#{post.user.name} (#{post.user.reputation_for(:points).to_i})", post.user %>
</span>