Featured post
ruby on rails - Trying to get counts through multiple associations -
i have created question answer app client stackoverflow. not trying implement sort of point system (like reputation). trying record counts through associations (which believe set correctly). trying counts votes on users answers. here example.
in /views/questions/show
page list answers question calling partial _answer.html.erb
. each answer pull in answer.user information (username, email, etc.) doing answer.user.username
. wanting display in badge format total point calculations. if user a
answered question a
, next user a
's answer want display total of user a
's answer votes.
i can count users answers in /views/answers/_answer.html.erb doing following:
<%= answer.user.answers.count %>
but when try extend syntax/association count of votes on user a
's answers undefined method errors.
<%= answer.user.answers.votes.count %>
is set fundamentally wrong here or missing something.
that bit confusing let me know if need more detail.
update:
here associations:
answers
class answer < activrecord::base belongs_to :question belongs_to :user has_many :votes, :dependent => :destroy end
votes
class vote < activerecord::base belongs_to :answer belongs_to :user belongs_to :question end
users
class user < activerecord::base has_many :questions, :dependent => :destroy has_many :answers, :dependent => :destroy has_many :votes, :through => :answers , :dependent => :destroy end
<%= answer.user.answers.votes.count %>
but
answer.user.answers
is array of answers suppose wanted like
<%= answer.user.answers[id].votes.count %>
update
<% answer.user.answers.each |answer| %> <%= answer.votes.count%> <% end% >
update
<%= (answer.user.answers.map{|x| x.votes.count}).sum%>
i love rails such things
- Get link
- X
- Other Apps
Comments
Post a Comment