ruby on rails - Array evaluating to nil -
below created class method in model called movie should return array:
def self.all_ratings array['g','pg','pg-13','r','nc-17'] end and in movies controller access using following instance variable:
@all_ratings = movie.all_ratings however when comes time use in index view receive following errors:
you have nil object when didn't expect it! might have expected instance of array. error occurred while evaluating nil.each i believe creating array wrong. suggestions why these errors occur?
below view @all_ratings used:
%h1 movies = form_tag movies_path, :method => :get include: - @all_ratings.each |rating| = rating = check_box_tag "ratings[#{rating}]" = submit_tag 'refresh' and here how implemented @all_ratings controller
class moviescontroller < applicationcontroller @all_ratings = movie.all_ratings
the code initialize instance variable needs in instance method.
(otherwise scope class, not instance.)
class moviescontroller < applicationcontroller def index # or wherever @all_ratings = movie.all_ratings end end if need value in several methods, use, say, before_filter.
ruby different languages like, say, java. in java, instance variables defined outside instance methods, , available in every instance method, whatever value initialized with.
in ruby, there 2 (major) ways handle instance variables: use method attr_accessor create accessor methods, or initialize them inside instance method, shown above.
once instance variable has initialized, value usable other instance method. example, in comments mention initializing in ratings method. unless ratings explicitly called, @all_ratings not initialized. in other words, if make get request index, ratings method not called, , @all_ratings still nil.
if explicitly call ratings index, @all_ratings initialized (by ratings method). once it's initialized in any instance method, instance of object (the controller in case) has initialized @all_ratings instance variable:
def index ratings end now value of @all_ratings available in index's template.
without putting instance variable initialization in instance method you're doing creating instance variable in class foo, different:
[1] pry(main)> class foo [1] pry(main)* @wat = self.class [1] pry(main)* end => class [2] pry(main)> f = foo.new => #<foo:0x007fbfba8efba8> [5] pry(main)> f.instance_variables => [] [6] pry(main)> foo.instance_variables => [:@wat] [7] pry(main)> foo.instance_eval "@wat" => class
Comments
Post a Comment