Rails method not available in view

I get this strange error. I defined a method for my 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

Then, on my controller, I define this instance:

@current_user_rating=@movie.ratings.where(:user_id => current_user)

And he finds it, so he works. But then, when I call a method, or a property like

<%= @current_user_rating.grade %>
<%= @current_user_rating.to_text %>

I get this error

undefined method `grade' for []:ActiveRecord::Relation
undefined method `to_text' for []:ActiveRecord::Relation

Why does a variable not behave as an instance with the corresponding attributes and methods, but as a relation?

It works on the console, but not on the server ...

+3
source share
2 answers

since the movie has several ratings, @current_user_rating is their collection, even if there is one. You should be able to get rid of errors by calling your methods as follows:

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

where, , , . .

first all . ( , , where rails, )

, , , :

@current_user_rating=@movie.ratings.where(:user_id => current_user).first

EDIT. , , GSto , , , . , , , . first .

, , . , , , , .

+2

Source: https://habr.com/ru/post/1787844/


All Articles