发布用户列表时 nil:NilClass 的未定义方法“名称”
Undefined method `name' for nil:NilClass when posting list of users
我正在尝试 post 用户列表 @shop.users
,这是 belong_to 一个商店的所有用户。
错误Undefined method 'name' for nil:NilClass
发生在我尝试渲染这部分
<div class="hero-unit user_info">
<h1><%= @user.name %></h1>
</div>
我想这是因为@user 没有 defined/iterated 正确显示给每个用户。我需要帮助才能正确地做到这一点。
这是 ShopsController 中的 customers 方法
def customers
@shop = Shop.find_by_id(params[:id])
@customers = @shop.users
end
这是页面 /customers
<div id="customers_feed">
<% if @customers.any? %>
<ul class="customers">
<%= render @customers %>
</ul>
<% else %>
<h3> No customers have added you as their designated shop yet.</h3>
<% end %>
</div>
其中 render @customers
开始我上面显示的部分,@user.name 得到错误。
我不确定如何正确定义 user
以便正确呈现属于商店的每个用户的姓名。我怎样才能使这项工作?
尝试将您的偏音更改为:
<div class="hero-unit user_info">
<% customers.each do |customer| %>
<h1><%= customer.name %></h1>
<% end %>
</div>
您的客户模板为:
<div id="customers_feed">
<% if @customers.any? %>
<ul class="customers">
<%= render partial "customers", locals: { customers: @customers } %>
</ul>
<% else %>
<h3> No customers have added you as their designated shop yet.</h3>
<% end %>
</div>
partials 中的集合渲染不使用实例变量,您需要删除 @user
并使用 user
:
<div class="hero-unit user_info">
<h1><%= user.name %></h1>
</div>
制作部分 _customer
并像这样更改您的代码
<div class="hero-unit user_info">
<h1><%= customer.name %></h1>
</div>
替换这个
<%= render @customers %>
到
<%= render 'customer', collection: @customers, as: :customer %>
我正在尝试 post 用户列表 @shop.users
,这是 belong_to 一个商店的所有用户。
错误Undefined method 'name' for nil:NilClass
发生在我尝试渲染这部分
<div class="hero-unit user_info">
<h1><%= @user.name %></h1>
</div>
我想这是因为@user 没有 defined/iterated 正确显示给每个用户。我需要帮助才能正确地做到这一点。
这是 ShopsController 中的 customers 方法
def customers
@shop = Shop.find_by_id(params[:id])
@customers = @shop.users
end
这是页面 /customers
<div id="customers_feed">
<% if @customers.any? %>
<ul class="customers">
<%= render @customers %>
</ul>
<% else %>
<h3> No customers have added you as their designated shop yet.</h3>
<% end %>
</div>
其中 render @customers
开始我上面显示的部分,@user.name 得到错误。
我不确定如何正确定义 user
以便正确呈现属于商店的每个用户的姓名。我怎样才能使这项工作?
尝试将您的偏音更改为:
<div class="hero-unit user_info">
<% customers.each do |customer| %>
<h1><%= customer.name %></h1>
<% end %>
</div>
您的客户模板为:
<div id="customers_feed">
<% if @customers.any? %>
<ul class="customers">
<%= render partial "customers", locals: { customers: @customers } %>
</ul>
<% else %>
<h3> No customers have added you as their designated shop yet.</h3>
<% end %>
</div>
partials 中的集合渲染不使用实例变量,您需要删除 @user
并使用 user
:
<div class="hero-unit user_info">
<h1><%= user.name %></h1>
</div>
制作部分 _customer
并像这样更改您的代码
<div class="hero-unit user_info">
<h1><%= customer.name %></h1>
</div>
替换这个
<%= render @customers %>
到
<%= render 'customer', collection: @customers, as: :customer %>