【发布时间】:2015-04-29 21:17:09
【问题描述】:
我正在尝试根据收视率的平均值订购指数。评级是评论模型上的整数属性。 以下是我的相关模型:
provider.rb
class Provider < ActiveRecord::Base
belongs_to :user, foreign_key: 'user_id', autosave: true
has_many :reviews, :through => :user, dependent: :destroy
def reviews
Review.where("provider_id = ?", id)
end
end
review.rb
class Review < ActiveRecord::Base
belongs_to :user, foreign_key: 'user_id'
belongs_to :provider, foreign_key: 'provider_id'
end
尝试访问视图中的提供程序属性时出现错误,如下所示:
index.html.erb
<% @providers.each do |provider| %>
<tr>
<td><%= link_to provider.name, provider_path(provider.id) %></td>
<td><%= provider.industry %></td>
<td><%= provider.tag %></td>
<td><%= provider.description %></td>
<td><%= provider.reviews.average(:rating) %></td>
</tr>
<% end %>
导致此问题的代码(我认为)在我的产品控制器中:
providers_controller.rb
class ProvidersController < ApplicationController
before_action :set_provider, only: [:show, :edit, :update, :destroy]
def index
@providers = Provider.select("avg(reviews.rating) as avg_rating").joins(:reviews).order("avg_rating DESC")
@reviews = Review.find_by(params[:provider_id])
end
我无法访问视图中列出的任何属性。我不确定问题出在我的视图代码还是控制器代码上。谢谢你的帮助。
错误
activerecord (4.2.1) lib/active_record/attribute_methods/read.rb:93:in `block in _read_attribute'
activerecord (4.2.1) lib/active_record/attribute_set.rb:31:in `block in fetch_value'
activerecord (4.2.1) lib/active_record/attribute.rb:150:in `value'
activerecord (4.2.1) lib/active_record/attribute_set.rb:31:in `fetch_value'
错误编辑
显示 /home/Danae/RubymineProjects/canvas/app/views/providers/index.html.erb 其中第 20 行提出:
缺少属性:名称
解决方案 我的菜鸟错误。有一个干扰 avg_rating 的列名。 cschroed 的回答很完美。
【问题讨论】:
-
你能发布整个错误,而不仅仅是“MissingAttributeError”吗?
-
那会是完整的跟踪吗?
-
通常是的。根据它的长度,您可能希望将其缩短为仅告诉您错误在哪里、行号等的最低级别的行。
-
带跟踪的已编辑问题。
-
app/views/providers/index.html.erb:20:inblock in _app_views_providers_index_html_erb___4343438652084474623_27379300'... 那一行的代码是什么?
标签: sql ruby-on-rails ruby-on-rails-4