$ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-linux]
$ rails -v
Rails 4.2.0
$ grep DESCR /etc/lsb-release
DISTRIB_DESCRIPTION="Ubuntu 16.04.1 LTS"
I'm trying to build and expose a subset of records to my view(s) from my controller like this:
@assigned_roles = @user.user_roles.select{|x| x.is_required }.map{ |ur| ur.role }
if @assigned_roles.blank?
@optional_roles = Role.all
else
@optional_roles = Role.where('id NOT IN (?)',@assigned_roles.map{ |r| r.id})
end
It works but I'm looking for something more elegant. the .where NOT IN doesn't work as I expect when @assigned_roles is empty.
I have models for Role and User which have many of eachother through user_roles which bears the t.boolean "is_required", default: true, null: false attribute.
Sorry I'm a total n00b so I don't know what else to include. Much Thanks!
'NOT IN'to do? Also, if@assigned_rolesis empty, your code shouldn't even be getting to the'NOT IN'call -- you should be falling intoRole.all. Is that not happening?not in (?)produces nonsense when the?is a placeholder for an empty array. That's why theif @assigned_roles.blank?is needed and the OP would prefer to not have to worry about whether or not@assigned_rolesis empty. This is more of "how do I make this code less ugly" question than a "why doesn't this work" question.