How do I update the same value from either a selection list or a textfield on the same form (Rails 3)?

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:&nbsp;<%= f.collection_select(:current_tutor, @tutors,
:name, :name, {:include_blank => true}) %></p>
<p>..or dd new tutor:&nbsp;<%= 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 }
     end
end

Answers


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.


Need Your Help

How to validate all tokens are valid in an NSTokenField

objective-c cocoa nstokenfield

Apple have conveniently created a callback method that allows you to check that the new tokens that are being added to an NSTokenField are valid:

create tile data in background agent wp7

windows-phone-7 background-process live-tile writablebitmap

What's a good way to create the bitmap needed to update a live tile in a background agent? In the UI thread, you use writeableBitmap class, but this does not work in the non-ui thread. There are many

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.