0
votes

I think my problem is really small, but I didn't found a good solution in the internet.

<%= form_tag url_for(controller: 'courses', action: 'add_teacher') , method: 'put' do%>
<%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| ([t._name, t.id] unless @course.teachers.include?(t))})%>
<%= hidden_field_tag(:course, value = @course.id) %>
<%= submit_tag 'hinzufügen' %>

I got this code in my courses/new View. I would like to add one or more teachers for one course, but i don't want to be able to add them twice or more. So I used this:

unless @course.teachers.include?(t)

The problem is, it still looks like this:empty rows

May anyone got a better solution for this problem? what happens if teachers = nil?

thank u for help

2
How many teachers do you intend to have on this app? An autocomplete field might be a better solution in the long run.Thomas R. Koll
@ThomasR.Koll Oh i would love to have a autocomplete field in my search functions. And maybe in this case as well. But I thought it will be too difficult. May u help me with it? :)homior
You need an autocomplete method on the controller and on the frontend there's plenty of javascript libraries for the job.Thomas R. Koll

2 Answers

1
votes

You did collection a few nil values which you can get rid of with the compact at the end.

<%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| ([t._name, t.id] unless @course.teachers.include?(t))}.compact )%>
1
votes

You can use compact to remove nil values.

<%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| ([t._name, t.id] unless @course.teachers.include?(t))}.compact )%>

or you can use the below method that will remove " " or nil values

<%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| ([t._name, t.id] unless @course.teachers.include?(t))}.select(&:presence) )%>

Example for select(&:prescence):

Teachers = ["mark", "robin", "", "jack", nil, "steve"]

Teachers .select(&:presence)

["mark", "robin", "jack", "steve"]

Example for compact:

Teachers = ["mark", "robin", "", "jack", nil, "steve"]

Teachers.compact

["mark", "robin","", "jack", "steve"]