bru*_*san 3 methods model ruby-on-rails
我收到这个奇怪的错误.我为我的模型定义了一个方法
class Rating < ActiveRecord::Base
[...]
belongs_to :user
belongs_to :movie
[...]
def to_text
texto = case self.grade
when 0..1 then "horrible"
when 2..3 then "bad"
when 4..5 then "not bad"
when 6..7 then "good"
when 8..9 then "very good"
when 10 then "master piece"
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后,在我的控制器上,我定义了这个实例:
@current_user_rating=@movie.ratings.where(:user_id => current_user)
Run Code Online (Sandbox Code Playgroud)
它确实找到了它,所以它有效.但是,当我调用方法或类似的属性时
<%= @current_user_rating.grade %>
<%= @current_user_rating.to_text %>
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
undefined method `grade' for []:ActiveRecord::Relation
undefined method `to_text' for []:ActiveRecord::Relation
Run Code Online (Sandbox Code Playgroud)
为什么变量不是具有适当属性和方法的实例,而是作为Relation?
它可以在控制台上运行,但不能在服务器上运行......
由于电影有多个评级,@ current_user_rating是它们的集合,即使有一个.你应该能够通过调用这样的方法来摆脱错误:
<% @current_user_rating.each do |rating| %>
<%= rating.grade %>
<%= rating.to_text %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
307 次 |
| 最近记录: |