hcarreras
hcarreras

Reputation: 4612

"if" or "unless" in a RoR model

I'm developing an application where you can log in by facebook or sign up. For this reason I have an Image that can be the facebook image or an upload image, but I don't know how to put this in the model.

My model:

class User < ActiveRecord::Base
  attr_accessible :name, :password, :password_confirmation, :big_image, :image, :mini_image

  validates_confirmation_of :password
  validates_presence_of :password, :on => :create, :unless => :from_facebook
  validates_presence_of :name
  validates_uniqueness_of :name   

  unless :from_facebook
    mount_uploader :big_image, ImageUploader
  end


  def from_facebook
    self.provider == "facebook"
  end

  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.big_image = auth.info.image.gsub("=square","=large")
      user.image = auth.info.image.gsub("=square","=normal")
      user.mini_image = auth.info.image
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

end

The part I want to change is:

unless :from_facebook
  mount_uploader :big_image, ImageUploader
end

because it doesn't work.

Upvotes: 2

Views: 128

Answers (1)

Simon Peck
Simon Peck

Reputation: 517

You don't want to conditionally call mount_uploader.

There are a couple of approaches to this problem:

1) Allow big_image to be nil for users who sign up with facebook and dynamically fetch their image from facebook if that's the case.

2) Save off the large version of their facebook image as big_image. That way you have all of the version sizes you need and you could even allow your users to override it later.

Upvotes: 1

Related Questions