0
votes

Hello i guess this is going to be pretty noob question.. But..

I have an scaffold called list, which has_many :wishes. And with that information in my model, I can in my list view use this code

well now I have made an controller called statusboard.. And in that' I have 3 functions.. Or how to say it.. but it is Index, loggedin, loggedout.. And .. In loggedin and in the file #app/views/statusboard/loggedin.html.erb i want to display this..

Howdy {Username}, you have made {count lists} lists, and {count wishes} wishes

here is that i figured i should write in my file..

Howdy {Username}, you have made <%=h @user.list.count %> lists, and <%=h @user.wishes.count %> wishes

my list model is like this =

class List < ActiveRecord::Base

  attr_accessible :user_id, :name, :description

  belongs_to :users

  has_many :wishes

end

and my wish model is like this =

class Wish < ActiveRecord::Base

  attr_accessible :list_id, :name, :price, :link, :rating, :comment

  belongs_to :list

end

and last my user model is like this =

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:

  # :token_authenticatable, :lockable and :timeoutable

  devise :database_authenticatable, :registerable,# :confirmable,

             :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model

  attr_accessible :email, :password, :password_confirmation

  has_many :lists

end

i hope someone can help me :-)! / Oluf Nielsen

3

3 Answers

0
votes

Add the has_many :through association for user:

class User < ActiveRecord::Base
  ...
  has_many :lists
  has_many :wishes, :through => :lists
end

and then you can use

@user.wishes.count
0
votes

Write this method in user model

#copy the below code in /app/models/user.rb file`
def wishes_count
  counter = 0
  self.lists.each do |list| # this is similar to @user.lists 
    counter += list.wishes.count #this is similar to @list.wishes
  end
  return counter
end

Howdy {Username}, you have made <%=h @user.list.count %> lists, and <%=h @user.wishes_count %> wishes

you can't use @user.wishes.count since user is not directly related to wishes, hope this solution works for you. If any questions please drop a comment.

0
votes

This is a little bit tangential, but it shouldn't be necessary to use the h html sanitizing helper method on:

<%=h @user.list.count %>

since count is a ruby generated method and not user created.