My current solution involves passing both values with 2 different variable names from the view to the controller and then using logic in the controller to decide which one to use for the update. It works, but I'm thinking there has to be a better way. Any advice?
=== view ===
<p>Choose tutor from list: <%= f.collection_select(:current_tutor, @tutors,
:name, :name, {:include_blank => true}) %></p>
<p>..or dd new tutor: <%= f.text_field :current_tutor_textfield %></p>
=== controller ===
respond_to do |format|
@student = Student.where(:slug => params[:id]).first
# Here I'm deciding which value will be passed to the update as the new_tutor
unless params[:student][:current_tutor].blank?
new_tutor = params[:student][:current_tutor]
end
unless params[:student][:current_tutor_textfield].blank?
new_tutor = params[:student][:current_tutor_textfield]
end
if @student.update_tutor(new_tutor)
format.html { redirect_to(students_path,
:notice => 'Student was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @post.errors,
:status => :unprocessable_entity }
开发者_Python百科 end
end
I don't know of a lot of better ways to do it, though I'd probably clean up the bit where you're deciding which tutor goes with @student. Those two statements are mutually exclusive, no? They could both execute at this point, unless your intent is that the new tutor name would override the selection of an existing tutor.
精彩评论