开发者

Trying to get counts through multiple associations

I have created a question an answer app for a client much like StackOverflow. I am not trying to implement some sort of point system (like开发者_C百科 SO reputation). I am trying to get certain record counts through associations (which I believe are set up correctly). Primarily I am trying to get counts for votes on users answers. Here is an example.

In /views/questions/show page I list all the answers to that question by calling a partial _answer.html.erb. With each answer I pull in the answer.user information (username, email, etc.) by simply doing answer.user.username. I am wanting to display in a badge like format some total point calculations. So if User A answered Question A, next to User A's answer I want to display a total of all User A's answer votes.

I can successfully get a count for a users answers in /views/answers/_answer.html.erb by doing the following:

<%= answer.user.answers.count %>

but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

<%= answer.user.answers.votes.count %> 

Is my set up fundamentally wrong here or am I missing something.

That is a bit confusing so let me know if you need more detail.

UPDATE:

Here are the 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 an array of answers so I suppose you wanted something like

<%= answer.user.answers[id].votes.count %> 

UPDATE

<% answer.user.answers.each do |answer| %>
    <%= answer.votes.count%>
<% end% >

UPDATE

 <%= (answer.user.answers.map{|x| x.votes.count}).sum%>

I LOVE rails for such things


but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.
You can find complete listing of what you can do with user.answers collection in here (besides standard Array/Enumerable methods). And it's only collection instance, not Answer object, so you can't invoke methods from Answer model on it.

You can try setupping has_many :votes, :through => :answers relationship. (See here for details) Although, I'm not sure if :through would work in such case.
Alternatively, you can create a method in User model to return all Vote objects (simply by iterating through all answers)

But frankly, creating a horde of Vote objects simply to count them sounds like a terrible waste of resources to me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜