users = User.includes(:office)
It will fire only two queries.
f.select :user_id, options_for_select(users.collect {|x| [x.name, x.id] if x.office.nil?}.compact), prompt: "Please select"
Or you can use join
.
Question
I have two models association looks like :
User
has_one Office
Office
belongs_to User
For Attrubutes looks like :
User
: id, name
Office
: id, user_id, address
Scenario for add new an office and select user looks like :
<%= f.select :user_id, options_for_select([["Choose User", "0"]] + User.all.collect {|x| [x.name, x.id] if Office.find_by_user_id(x.id).nil? == true }), {}%>
If the user have an office, the user doesn't display in select tag.
Problem :
I have one user 'A', User 'A' appear on select tag when add new an office.
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option value="1">A</option></select>
When I add new an office again, select tag have blank option.
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option></option></select>
When I have two user : user 'A' haven't an office and user 'B' too.
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option value="1">A</option>
<option value="2">B</option></select>
User 'A' have an office and user 'B' haven't
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option></option>
<option value="2">B</option></select>
User 'B' have an office and user 'A' haven't
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option value="1">A</option>
<option></option></select>
User 'A' have an office and user 'B' too
<select id="office_user_id" name="office[user_id]"><option value="0">Choose User</option>
<option></option>
<option></option></select>
etc.
La solution
users = User.includes(:office)
It will fire only two queries.
f.select :user_id, options_for_select(users.collect {|x| [x.name, x.id] if x.office.nil?}.compact), prompt: "Please select"
Or you can use join
.