Rickmasta
Rickmasta

Reputation: 449

How do I make an method for an object in rails?

Hey guys, so I have two models in my project, grinders, and votes.

So each grinder has many votes, and votes belongs to grinder.

The votes table has 3 columns: grinder_id:integer, choice:string, and voter_ip:string

How and WHERE can I make a method for my grinders? I want to be able to do something like

<% @grinders.each do |grinder| %>
  <%= grinder.votes_up %>
<% end %>

Where do I define this?

def self.votes_up 
  grinder.votes.find(:all, :choice => "up").count
end

If that is the right way to do it, correct me if I'm wrong, please.

Upvotes: 1

Views: 42

Answers (1)

Peter
Peter

Reputation: 132407

inside app/models/grinders.rb you should write

class Grinder < ActiveRecord::Base
  def votes_up
    count "choice = 'up'"
  end
end

Upvotes: 4

Related Questions