uvytautas
uvytautas

Reputation: 528

Where to write this method in Model or Controller?

I am new at rails and the more on MVC. So I have a model called Bet, it has attributes: id, odd, description, outcome. I want to write methods set_won that would change outcome to 1 and set_lost that would change outcome to 0.

I am not quite sure where to implement these methods in Model or in Controller?

Upvotes: 0

Views: 858

Answers (3)

Tucker
Tucker

Reputation: 659

You should write it in the model.

In your controller you'll call an action "BetController#update" or whatever you would like, then do something like this:

class BetController < ApplicationController
   ...
   def update
     #do somestuff
     @bet.set_won or @bet.set_lost
   end

  -------

  class Bet < ActiveRecord::Base
    #some stuff up here
    def set_won
      self.outcome = 1
    end

    def set_lost
      self.outcome = 0
    end
  end

Upvotes: 2

David Aldridge
David Aldridge

Reputation: 52336

I would suggest that you look into using an enum for this, whereby you set values on your outcome attribute as one of "None", "Won", or "Lost".

An enum will provide you with the getter and setter methods, and scopes for listing all won or lost bets.

http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

Upvotes: 3

Raman
Raman

Reputation: 1281

You can write this code in Model as it is specific to setting an attribute in Bet Model. Also as Rails has the saying "Fat Model Skinny Controller", a model would be a better fit.

Upvotes: 0

Related Questions