开发者

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

开发者 https://www.devze.com 2023-01-28 13:41 出处:网络
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 wo

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 }
   开发者_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消