Ruby on rails 运行时错误RoR…调用了nil的id,这将错误地
在我的商户索引页面上,我试图显示当前登录用户对每个特定商户的信用额度。请注意,列表中可能有用户没有信用的商户 商户索引中的运行时错误 显示第9行出现的…/app/views/merchants/index.html.erb: 为nil调用id,它会错误地为4——如果您确实想要nil的id,请使用object_idRuby on rails 运行时错误RoR…调用了nil的id,这将错误地,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在我的商户索引页面上,我试图显示当前登录用户对每个特定商户的信用额度。请注意,列表中可能有用户没有信用的商户 商户索引中的运行时错误 显示第9行出现的…/app/views/merchants/index.html.erb: 为nil调用id,它会错误地为4——如果您确实想要nil的id,请使用object_id <ul class="list-group"> <% @merchants.each do |merchant| %> <a
<ul class="list-group">
<% @merchants.each do |merchant| %>
<a href="/merchants/<%= merchant.id %>" class="list-group-item "><%= merchant.name %>
<% if Credit.where(:user_id => @current_user.id, :merchant_id => merchant.id).count > 0 %>
line9-> <%= Credit.where(:user_id => @current_user.id, :merchant_id => merchant.id).sum(:amount) %>
<% end %>
</a>
<% end %>
</ul>
提前感谢。不要在视图中使用纯SQL—这就是控制器的用途 您应该这样做:
#app/models/credit.rb
class Credit < ActiveRecord::Base
scope :active, -> { where("amount IS NOT NULL") }
end
#app/controllers/credits_controller.rb
def index
@credits = current_user.credits.active #-> only shows active credits
end
#app/views/credits/index.html.erb
<ul class="list-group">
<% @merchants.each do |merchant| %>
<a href="/merchants/<%= merchant.id %>" class="list-group-item "><%= merchant.name %>
<%= @credits.sum(:amount) if @credits.present? %>
</a>
<% end %>
#app/models/credit.rb
类信用{where(“金额不为空”)}
结束
#app/controllers/credits_controller.rb
def索引
@信用=当前_user.credits.active#->仅显示活动信用
结束
#app/views/credits/index.html.erb
谢谢Rich,我想我明白你的意思,不要在视图中使用纯SQL。但问题是,如果我像你建议的那样使用代码,我会得到每个商户列表组项目的用户在系统中拥有的信用总额。我需要迭代每个商户,在每个商户列表组项目上显示用户与该特定商户的信用总额。我清楚了吗?错误意味着
@当前用户
或商户
为零@理查德·佩克下面的建议也很好。