Frage

I'm a bit dumfounded - getting an 'undefined method `each' for nil:NilClass' error.

I've created a pretty straight-forward scope in the model

  def self.just_added
      where('created_at > ?', Time.now-7.days.ago).order("created_at desc").first(4)
  end

And a loop in my view

<% @just_added_jobs.each do |job| %>
    <%= link_to job.name, job %>         
<% end %>

Not sure what's going on - I'm fairly certian I've created a scope like before that worked fine.

Also - I also plan to do some more complex scoping with dates - I have several date fields as part of a model (i.e., to loop through the jobs that are due soon, past due). Where could I read more about scoping dates?

War es hilfreich?

Lösung

  1. The result of the classmethod you show can never be nil so we must conclude you're failing to set @just_added_jobs in the controller.

  2. created_at > Time.now-7.days.ago makes no sense, you probably mean created_at > 7.days.ago

  3. Calling first(n) on a scope is a bad idea because the result is not a scope anymore but an array. You need limit(n).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top