Create a variable in after_find of model in Ruby on Rails

I need generate a variable for send a the view, for example i have this:

def after_find
    unless self.photo.nil?
        if File.exist?(Rails.root + 'public/uploads/tournaments/' +  self.photo)
            self.photo = '/uploads/tournaments/' + self.photo
        else
            self.photo = "http://placehold.it/250x400"
        end
    else    
        self.photo = "http://placehold.it/250x400"
    end
end

It runs well that variable is an attribute of db migration,the problem is when I declare something that is not an attribute of db migration

self.variable1 = "hello world"

enter image description here

Upvotes: 0

Views: 124

Answers (1)

Mike Szyndel
Mike Szyndel

Reputation: 10592

If you want to have an attribute on a model but this attribute is not part of your database you can define it as accessor. In your model just add

#app/models/tournament.rb
class Tournament < ActiveRecord::Base
   attr_accessor :variable1
end

EDIT:

However in this particular case you should consider the performance penalty from checking the filesystem every time you load a Tournament object.

Using gem like Carrierwave or Paperclip is a much better solution!

Upvotes: 3

Related Questions