Reputation: 2705
I have an organisation model, which has an attribute called org_type
. In my organisation form, I ask users to specify whether their org type is university, college or other kinds of organisation. In my show page, I want to show some text if the org type is university or college.
I can't get the either or function working. If I just ask to check one org type, such as below, it works fine:
<% if @organisation.org_type == 'University' %>
If I ask for either org type, it shows everything even where the test org is 'other':
<% if @organisation.org_type == 'University' or 'College' %>
The above doesn't work. It shows the text where the org type is 'other'.
Can anyone see what I've done wrong?
Upvotes: 0
Views: 442
Reputation: 3963
Logic in the view like that risks getting complex and hard to maintain. It always starts as just one check for those couple of conditions, then gets copied to half-a-dozen places, then the condition changes to "uni, college or self-study" and you've got to find all the places you used it.
Better to extract it to a method in the model, and then have the views just ask the model.
# Organisation model
def uni_or_college?
%w(University College).include? org_type
end
# view
<% if @organisation.uni_or_college? %>
...
<% end %>
This is also a testable approach - if you have tests that ensures the .uni_or_college?
method returns what's expected, if (when) the requirements change in future, you have a safety net to help with your refactoring.
Upvotes: 1
Reputation: 5905
rails actually runs below if condition as two separate conditions.
<% if @organisation.org_type == 'University' or 'College' %>
@organisation.org_type == 'University'
is true OR 'College'
.
means, <% if (@organisation.org_type == 'University') || ('College') %>
To overcome this situation, you can do something like that:
<% if ['University', 'College'].include?(@organisation.org_type) %>
It would return true if @organisation.org_type
is either 'University' or 'College'. Else false
Upvotes: 2