jordan.baucke
jordan.baucke

Reputation: 4328

Activerecord relationship joins

I'm working in Rails and Activerecord and trying to merge some data from related tables together in my view, here are my models:

class Report < ActiveRecord::Base
  has_many :votes
end

class Vote < ActiveRecord::Base
  belongs_to :reports
end

class User < ActiveRecord::Base
  has_many :votes
end

Each vote has a user and a report.

In my view I need the following, hopefully as easily as possible:

  1. a total number of votes for each report from all users
  2. a true/false if the user has voted on the particular report

Right now, my basic understanding of ActiveRecord queries only takes me as far as creating a helper with the report and the current user and than querying for the existence of report

Same goes for counting the total number of votes for all users for a report as follows:

Controller

def index
  #this is where I need some help to get the related information into a single
  #object
  @reports = Report.where('...')
end

View

<% @reports.each do |report| %>
    <% if(hasVoted(@current_user.id, report.id)) %>
        <!-- display the 'has voted html' -->
    <% end %>
<% end %>

Helper

def hasVoted(current_user_id, report_id)
    if(Vote.exists?(:user_id => current_user_id, :report_id => report_id))
      true
    else
      false
    end      
end

Hope that gives you some insight into helping...thanks!

Upvotes: 0

Views: 65

Answers (1)

Aditya Sanghi
Aditya Sanghi

Reputation: 13433

Sure.

Firstly, please consider naming your method has_voted? instead of hasVoted. Secondly, consider moving that method in the user model.

#user.rb
def voted_on?(report_id)
  votes.where(:report_id => report_id).exists?
end

Your view will then read

<% if current_user.voted_on?(report) %>
  ...
<% end %>

The other question you had was to find the number of votes a report has received. This is simple too. You could do this in your view inside the loop where you iterate over @reports

<% vote_count = report.votes.size %>

Please keep in mind that his would result in N queries (where N = number of reports). Since you are new to Rails i'm not going to complicate your Reports query in the controller where you fetch you reports to include the vote count (unless you ask me to). But once you are comfortable with what happening in here, thats where you would optimize.

Upvotes: 1

Related Questions