开发者

rails use counts in different views

开发者 https://www.devze.com 2022-12-31 02:55 出处:网络
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

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 i开发者_运维技巧s 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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消