簡體   English   中英

如何從選擇列表或同一表單上的文本字段中更新相同的值(第3條)?

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

我當前的解決方案包括將兩個帶有兩個不同變量名的值從視圖傳遞到控制器,然后使用控制器中的邏輯來決定使用哪個值進行更新。 它有效,但是我認為必須有更好的方法。 有什么建議嗎?

===視圖===

<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>

===控制器===

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

我不知道有很多更好的方法可以做到這一點,盡管我可能會整理一下您決定與@student一起使用的導師的位置。 這兩個陳述是互斥的,不是嗎? 他們都可以在這時執行,除非您的意圖是新的教師姓名將覆蓋對現有教師的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM