I have set @user_ctypes, but, when I access to it from a model, I get a Nil value. Why?
This is a TV Guide and an user (current_user) will set which are channels that it want to hide. For example: If the logged user doesn't have a satellite, he will have ctypes=['sat']. So any channels that is aired on satellite will be hidden to user. If user is not logged, current_user is nil.
I'd want to use "default_scope" because any query to DB should be take care of which channels the user wants to see.
ApplicationController
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :set_user_ctypes
private
def set_user_ctypes
unless current_user.nil?
@user_ctypes = current_user.ctypes
else
@user_ctypes = Array.new
end
end
Model
class Channel < ActiveRecord::Base
has_many :programs, :dependent => :delete_all
validates :name, :site, :ctype, :country, :presence => true
default_scope {where.not(ctype: @user_ctypes)}
User (by Devise)
class User < ActiveRecord::Base
unless/else, I'd suggest changing the code so you can useif/else. It will improve the readability of the code.