I have a controller that sorts the order of objects based on their numeric position:
<%= form_for @subject do |f| %>
<p><%= f.label :position %></p>
<p><%= f.select :position, 1..@subject_count %></p>
<% end %>
Presumably if someone wanted to create a new subject, an additional numeric position would be added to the select box. So for instance, if there were 5 subjects and someone wanted to add another there would be 6 positions to select from.
Here's how I currently have my controller set up.
def new
@subject = Subject.new
@subject_count = Subject.count + 1
end
def create
@subject = Subject.new(subject_params)
@subject_count = Subject.count + 1
end
def edit
@subject_count = Subject.count
end
def update
@subject_count = Subject.count
...
end
private
def subject_params
params.require(:subject).permit(:name, :position, :visible)
end
def set_subject
@subject = Subject.find(params[:id])
@subject_count = Subject.count
end
I'd like to keep this code DRY by using a before_action that would add 1 to the Subject.count
only on the new and create actions in one method. Is there a way to setup a conditional that I could accomplish this? Here's what I had in mind:
def_set_subject_count
# if new || create actions are requested
# @subject_count = Subject.count + 1
# elseif edit || update actions are requested
# @subject_count = Subject.count
# end
end