jeudi 23 juin 2016

Query from database does not return in rails

My rails app has a User model and a Role model. Each User belongs to one role and each role has many users. There three methods defined in the user model to check the role of that user def admin?, def user?, and def expert?.

The User class:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader

  validates_presence_of :name
  validates_presence_of   :avatar
  validates_integrity_of  :avatar
  validates_processing_of :avatar

  before_save :assign_role
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  belongs_to :role
  has_many :items
  belongs_to :organization
  has_many :expertkeywordmodels
  has_many :keywords, through: :expertkeywordmodels

  def assign_role
    self.role = Role.find_by name: "Admin" if self.role.nil?
  end

  def self.with_role(role)
     my_role = Role.find_by_name(role)
     where(:role => my_role)
  end

  def admin?
    self.role.name == "Admin"
  end

  def user?
    self.role.name == "User"
  end

  def expert?
    self.role.name == "Expert"
  end

end

The Role class:

class Role < ActiveRecord::Base
  has_many :users
end

I am trying to create a collection_select only with users that have expert role. Something like:

<%= collection_select(:keyword, :user_ids, User.where('expert?'), :id, :name, {prompt: true}, {:multiple => true}) %>

But it does not recognize expert? as a method. I was wondering if anyone knows how can I perform this query. I am sorry if this is a naive question as I am new to rails.

Thanks, Amir

Aucun commentaire:

Enregistrer un commentaire