Rails将对象传递给Partials

时间:2014-08-15 02:33:19

标签: ruby-on-rails ruby-on-rails-4 view partial-views dry

我有很多形式开头:

<% if @user.errors.any? %>
  <div class="alert alert-danger", id="error">
    <p>Please correct the following error(s):</p>
    <ul>
    <% @user.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  </div>
<% end %>

只有我有@ user,@ item等等,所以我想这样干它:

<%= render "layouts/errors", locals: { obj: @status } %>

<!-- layouts/errors file -->
<% if obj.errors.any? %>
  <div class="alert alert-danger", id="error">
    <p>Please correct the following error(s):</p>
    <ul>
    <% obj.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  </div>
<% end %>

但这会导致错误:ActionView::Template::Error: undefined local variable or method obj'代表#&lt;#:0x007fce0c36a858&gt;`

如何成功传递此对象?

1 个答案:

答案 0 :(得分:0)

在致电partial:时尝试使用render密钥:

<%= render partial: "layouts/errors", locals: { obj: @status } %>