1

我有一个带有帖子的简单博客应用程序。

我使用部分_post.html.erb来呈现我的索引页面中的帖子。

_post.html.erb有一个 divclass=submission_details与我的show操作中使用的相同。我怎样才能将该部分分割出来,以便我可以在_post.html.erb部分和show.html.erb页面中使用它?

post_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如下部分:

共享/_submission_details.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>

show这由 为动作渲染render 'shared/submission_details',但在动作中给了我 nil index。如何为操作正确定义 @post index

4

1 回答 1

1

在局部上,您可以定义一个局部变量,当您渲染局部时,正确的语法是:

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>
于 2013-03-31T08:50:21.180 回答