views:

17

answers:

1

I am trying to figure out how to display a count for records that have been created in a table since the last_request_at of a user.

In my view I am counting the notes of a question with the following code:

<% unless @questions.empty? %>
  <% @questions.each do |question| %>
    <%= h(question.notes.count) %>
  end
end

This is happening in the /views/users/show.html.erb file. Instead of counting all the notes for the question, I would only like to count the notes that have been created since the users last_request_at datetime. I don't neccessarily want to scope notes to display this 'new notes' count application wide, just simply in this one instance.

To accomplish I am assuming I need to create a variable in the User#show action and call it in the view but not really sure how to do that.

Other information you may need:

class Note < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
end


class Question < ActiveRecord::Base
  has_many :notes, :dependent => :destroy
  belongs_to :user
end
+1  A: 

Just create a named scope and then use it only when it applies:

class Note < ActiveRecord::Base
  named_scope :added_since, lambda { |time| {
    :conditions => time && [ 'created_at>=?', time ]
  }}
end

This should only enforce conditions if a time is provided. If you submit a nil time, the default behavior is to scope all notes.

This way you can do something along the lines of:

@new_notes = @user.notes.added_since(@user.last_login_at)

Adding a named scope does not alter the default scope.

tadman