ruby-on-rails - Rails 方法在 View 中不可用

标签 ruby-on-rails methods model

我收到这个奇怪的错误。我已经为我的模型定义了一个方法

    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

然后,在我的 Controller 上,我定义了这个实例:
@current_user_rating=@movie.ratings.where(:user_id => current_user)

它确实找到了它,所以它有效。但是,当我调用该方法或类似的属性时
<%= @current_user_rating.grade %>
<%= @current_user_rating.to_text %>

我收到这个错误
undefined method `grade' for []:ActiveRecord::Relation
undefined method `to_text' for []:ActiveRecord::Relation

为什么变量不表现为具有适当属性和方法的实例,而是表现为关系?

它在控制台上有效,但在服务器上无效...

最佳答案

由于一部电影有多个评分,@current_user_rating 是它们的集合,即使有一个。您应该能够通过像这样调用您的方法来消除错误:

<% @current_user_rating.each do |rating| %>
  <%= rating.grade %>
  <%= rating.to_text %>
<% end %>

关于ruby-on-rails - Rails 方法在 View 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4800453/

相关文章:

node.js - Strongloop(环回)类方法

java - 如何使用枚举的 getter?

ruby-on-rails - 无法推送到 heroku - 捆绑程序失败

ruby-on-rails - rvm installation -/usr/local/rvm : permission denied (Before this, 我在 Ubuntu 中误删除了主目录)

ruby-on-rails - bundle 安装时烦人的 'Network error while fetching'

ios - 在 Obj-c 中使用 truncatingRemainder() 方法

java - Java 中 System.arraycopy 的异常

php - Cakephp "virtual"与另一个数据库一起使用的模型名称

python - sklearn 如何使用多个保存的模型合并和预测数据

ruby-on-rails - 摩卡 : How to add expectation of a method when there are multiple invocations with different parameters