我有一个简单的博客应用程序。
我使用部分_post.html.erb
来呈现我的索引页中的帖子。
_post.html.erb
有一个div class=submission_details
,它与我的show
行动中使用的相同。我如何将该部分偏出,以便我可以在_post.html.erb
部分和show.html.erb
页面中使用它?
posts_controller.rb
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
文章/index.html.erb
<%= render @posts %>
文章/_post.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>
文章/show.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>
我试着做一个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>
这是render 'shared/submission_details'
渲染的show
动作,但在index
动作中给了我nil。我如何正确定义@post的index
行动?
在分部中,您可以定义一个局部变量,当您呈现分部时,正确的语法应该是:
render(partial: 'post_information', locals: { post: @post }
但可以缩写为
render('post_information', post: @post)
用于show操作,对于部分_post.html而言。erb,你的post实例不是在变量@post上,而是在本地变量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>